2 # DSL - easy Display Setup for Laptops
3 # Copyright (C) 2012 Ralf Jung <post@ralfj.de>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program (gpl.txt); if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 import os, sys, re, subprocess
20 from PyQt4 import QtGui
21 from selector_window import PositionSelection
22 app = QtGui.QApplication(sys.argv)
24 # for auto-config: common names of internal connectors
25 commonInternalConnectorNames = ['LVDS', 'LVDS1', 'LVDS-0']
27 # Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
28 def loadConfigFile(file):
31 if not os.path.exists(file):
32 return result # no config file
35 with open(file) as file:
39 if not len(line) or line.startswith("#"): continue # skip empty and comment lines
42 pos = line.index("=") # will raise exception when substring is not found
43 curKey = line[:pos].strip()
44 result[curKey] = shlex.split(line[pos+1:]) # shlex.split also strips
46 raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)" % linenr)
47 # add some convencience get functions
50 def getXrandrInformation():
51 p = subprocess.Popen(["xrandr", "-q"], stdout=subprocess.PIPE)
52 connectors = {} # map of connector names to a list of resolutions
53 connector = None # current connector
56 if line.startswith("Screen"):
59 m = re.search(r'^([\w\-]+) (dis)?connected ', line)
61 connector = m.groups()[0]
62 assert connector not in connectors
63 connectors[connector] = []
66 m = re.search(r'^ ([\d]+)x([\d]+) +', line)
68 assert connector is not None
69 connectors[connector].append((int(m.groups()[0]), int(m.groups()[1])))
71 if p.returncode != 0: raise Exception("Querying xrandr for data failed")
76 return str(w)+'x'+str(h)
81 ratio = int(round(16.0*h/w))
82 if ratio == 12: # 16:12 = 4:3
84 elif ratio == 13: # 16:12.8 = 5:4
86 else: # let's just hope this will never be 14 or more...
87 strRatio = '16:%d' % ratio
88 return '%dx%d (%s)' %(w, h, strRatio)
90 def findAvailableConnector(tryConnectors):
91 for connector in tryConnectors:
92 if connector in connectors and connectors[connector]: # if the connector exists and is active (i.e. there is a resolution)
96 # load connectors and options
97 connectors = getXrandrInformation()
98 config = loadConfigFile(os.getenv('HOME') + '/.dsl.conf')
99 # find internal connector
100 if 'internalConnector' in config:
101 if len(config['internalConnector']) != 1:
102 raise Exception("You must specify exactly one internal connector")
103 internalConnector = config['internalConnector'][0]
104 if not internalConnector in connectors:
105 raise Exception("Connector %s does not exist, there is an error in your config file" % internalConnector)
108 internalConnector = findAvailableConnector(commonInternalConnectorNames)
109 if internalConnector is None:
110 raise Exception("Could not automatically find internal connector, please use ~/.dsl.conf to specify it manually")
111 # all the rest is external then, obviously - unless the user wants to do that manually
112 if 'externalConnectors' in config:
113 externalConnectors = config['externalConnectors']
114 for connector in externalConnectors:
115 if not connector in connectors:
116 raise Exception("Connector %s does not exist, there is an error in your config file" % internalConnector)
118 externalConnectors = connectors.keys()
119 externalConnectors.remove(internalConnector)
120 if not externalConnectors:
121 raise Exception("No external connector found - either your config is wrong, or your machine has only one connector")
123 # default: screen off
124 args = {} # maps connector names to xrand arguments
125 for c in externalConnectors+[internalConnector]:
129 usedExternalConnector = findAvailableConnector(externalConnectors) # *the* external connector which is actually used
130 if usedExternalConnector is not None: # there's an external screen connected, we need to ask what to do
131 internalResolutions = connectors[internalConnector]
132 externalResolutions = connectors[usedExternalConnector]
133 extPosition = PositionSelection(usedExternalConnector, map(res2user, internalResolutions), map(res2user, externalResolutions))
135 if not extPosition.result(): sys.exit(1) # the user canceled
136 extResolution = res2xrandr(externalResolutions[extPosition.extResolutions.currentIndex()])
137 intResolution = res2xrandr(internalResolutions[extPosition.intResolutions.currentIndex()])
139 args[usedExternalConnector] = ["--mode", extResolution] # set external screen to desired resolution
140 if extPosition.extOnly.isChecked():
141 args[usedExternalConnector] += ["--primary"]
143 # there are two screens
144 args[internalConnector] = ["--mode", intResolution] # set internal screen to desired resolution
146 if extPosition.posLeft.isChecked():
147 args[usedExternalConnector] += ["--left-of", internalConnector]
149 args[usedExternalConnector] += ["--right-of", internalConnector]
151 if extPosition.primExt.isChecked():
152 args[usedExternalConnector] += ["--primary"]
154 args[internalConnector] += ["--primary"]
156 # use first resolution
157 args[internalConnector] = ["--mode", res2xrandr(connectors[internalConnector][0]), "--primary"]
161 call += ["--output", name] + args[name]
162 print "Call that will be made:",call
163 subprocess.check_call(call)