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, re, subprocess
22 # for auto-config: common names of internal connectors
23 commonInternalConnectorNames = ['LVDS', 'LVDS0', 'LVDS1', 'LVDS-0', 'LVDS-1']
25 # this is as close as one can get to an enum in Python
26 class RelativeScreenPosition:
31 # Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
32 def loadConfigFile(file):
35 if not os.path.exists(file):
36 return result # no config file
39 with open(file) as file:
43 if not len(line) or line.startswith("#"): continue # skip empty and comment lines
46 pos = line.index("=") # will raise exception when substring is not found
47 curKey = line[:pos].strip()
48 result[curKey] = shlex.split(line[pos+1:]) # shlex.split also strips
50 raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)." % linenr)
51 # add some convencience get functions
54 def getXrandrInformation():
55 p = subprocess.Popen(["xrandr", "-q"], stdout=subprocess.PIPE)
56 connectors = {} # map of connector names to a list of resolutions
57 connector = None # current connector
60 m = re.search(r'^Screen [0-9]+: ', line)
61 if m is not None: # ignore this line
65 m = re.search(r'^([\w\-]+) (dis)?connected ', line)
67 connector = m.groups()[0]
68 assert connector not in connectors
69 connectors[connector] = []
72 m = re.search(r'^ ([\d]+)x([\d]+) +', line)
74 assert connector is not None
75 connectors[connector].append((int(m.groups()[0]), int(m.groups()[1])))
78 # not fatal as my xrandr shows strange stuff when a display is enabled, but not connected
79 #raise Exception("Unknown line in xrandr output:\n"+line)
80 print "Warning: Unknown xrandr line %s" % line
81 # be sure to always proprly finish up with the xrandr
83 # if everything succeededso far, check return code
84 if p.returncode != 0: raise Exception("Querying xrandr for data failed.")
89 return str(w)+'x'+str(h)
94 ratio = int(round(16.0*h/w))
95 if ratio == 12: # 16:12 = 4:3
97 elif ratio == 13: # 16:12.8 = 5:4
99 else: # let's just hope this will never be 14 or more...
100 strRatio = '16:%d' % ratio
101 return '%dx%d (%s)' %(w, h, strRatio)
103 def findAvailableConnector(tryConnectors, allConnectors):
104 for connector in tryConnectors:
105 if connector in allConnectors and allConnectors[connector]: # if the connector exists and is active (i.e. there is a resolution)
111 # load connectors and options
112 connectors = getXrandrInformation()
113 config = loadConfigFile(os.getenv('HOME') + '/.dsl.conf')
114 # find internal connector
115 if 'internalConnector' in config:
116 if len(config['internalConnector']) != 1:
117 raise Exception("You must specify exactly one internal connector.")
118 internalConnector = config['internalConnector'][0]
119 if not internalConnector in connectors:
120 raise Exception("Connector %s does not exist, there is an error in your config file." % internalConnector)
123 internalConnector = findAvailableConnector(commonInternalConnectorNames, connectors)
124 if internalConnector is None:
125 raise Exception("Could not automatically find internal connector, please use ~/.dsl.conf to specify it manually.")
126 # all the rest is external then, obviously - unless the user wants to do that manually
127 if 'externalConnectors' in config:
128 externalConnectors = config['externalConnectors']
129 for connector in externalConnectors:
130 if not connector in connectors:
131 raise Exception("Connector %s does not exist, there is an error in your config file." % connector)
132 if connector == internalConnector:
133 raise Exception("%s is both internal and external, that doesn't make sense." % connector)
135 externalConnectors = connectors.keys()
136 externalConnectors.remove(internalConnector)
137 if not externalConnectors:
138 raise Exception("No external connector found - either your config is wrong, or your machine has only one connector.")
140 # default: screen off
141 args = {} # maps connector names to xrand arguments
142 for c in externalConnectors+[internalConnector]:
146 usedExternalConnector = findAvailableConnector(externalConnectors, connectors) # *the* external connector which is actually used
147 if usedExternalConnector is not None: # there's an external screen connected, we need to ask what to do
148 internalResolutions = connectors[internalConnector]
149 externalResolutions = connectors[usedExternalConnector]
150 dialogue = gui.getDialogue(usedExternalConnector, map(res2user, internalResolutions), map(res2user, externalResolutions))
151 if not dialogue.run(): sys.exit(1) # the user canceled
152 extResolution = res2xrandr(externalResolutions[dialogue.getExtResolutionIndex()])
153 intResolution = res2xrandr(internalResolutions[dialogue.getIntResolutionIndex()])
154 relPosition = dialogue.getRelativeScreenPosition()
156 args[usedExternalConnector] = ["--mode", extResolution] # set external screen to desired resolution
157 if relPosition == RelativeScreenPosition.EXTERNAL_ONLY:
158 args[usedExternalConnector] += ["--primary"]
160 # there are two screens
161 args[internalConnector] = ["--mode", intResolution] # set internal screen to desired resolution
163 if relPosition == RelativeScreenPosition.LEFT:
164 args[usedExternalConnector] += ["--left-of", internalConnector]
166 args[usedExternalConnector] += ["--right-of", internalConnector]
168 if dialogue.externalIsPrimary():
169 args[usedExternalConnector] += ["--primary"]
171 args[internalConnector] += ["--primary"]
173 # use first resolution
174 args[internalConnector] = ["--mode", res2xrandr(connectors[internalConnector][0]), "--primary"]
178 call += ["--output", name] + args[name]
179 print "Call that will be made:",call
180 subprocess.check_call(call)
182 # if we run top-level
183 if __name__ == "__main__":
186 except Exception as e: