added experimental code for a zenity "gui", yet untested as I can't find my vga cable
[lilass.git] / dsl.py
1 #!/usr/bin/python
2 # DSL - easy Display Setup for Laptops
3 # Copyright (C) 2012 Ralf Jung <post@ralfj.de>
4 #
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.
9 #
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.
14 #
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.
18
19 import argparse, sys, os, re, subprocess
20 import gui
21
22 # for auto-config: common names of internal connectors
23 commonInternalConnectorNames = ['LVDS', 'LVDS0', 'LVDS1', 'LVDS-0', 'LVDS-1']
24
25 # this is as close as one can get to an enum in Python
26 class RelativeScreenPosition:
27         LEFT          = 0
28         RIGHT         = 1
29         EXTERNAL_ONLY = 2
30
31 # storing what's necessary for screen setup
32 class ScreenSetup:
33         def __init__(self, relPosition, intResolution, extResolution, extIsPrimary = False):
34                 '''relPosition must be one of the RelativeScreenPosition members, the resolutions must be (width, height) pairs'''
35                 self.relPosition = relPosition
36                 self.intResolution = intResolution # value doesn't matter if the internal screen is disabled
37                 self.extResolution = extResolution
38                 self.extIsPrimary = extIsPrimary or self.relPosition == RelativeScreenPosition.EXTERNAL_ONLY # external is always primary if it is the only one
39         
40         def getInternalArgs(self):
41                 if self.relPosition == RelativeScreenPosition.EXTERNAL_ONLY:
42                         return ["--off"]
43                 args = ["--mode", res2xrandr(self.intResolution)] # set internal screen to desired resolution
44                 if not self.extIsPrimary:
45                         args.append('--primary')
46                 return args
47         
48         def getExternalArgs(self, intName):
49                 args = ["--mode", res2xrandr(self.extResolution)] # set external screen to desired resolution
50                 if self.extIsPrimary:
51                         args.append('--primary')
52                 if self.relPosition == RelativeScreenPosition.LEFT:
53                         args += ['--left-of', intName]
54                 elif self.relPosition == RelativeScreenPosition.RIGHT:
55                         args += ['--right-of', intName]
56                 return args
57
58 # Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
59 def loadConfigFile(file):
60         import shlex
61         result = {}
62         if not os.path.exists(file):
63                 return result # no config file
64         # read config file
65         linenr = 0
66         with open(file) as file:
67                 for line in file:
68                         linenr += 1
69                         line = line.strip()
70                         if not len(line) or line.startswith("#"): continue # skip empty and comment lines
71                         try:
72                                 # parse line
73                                 pos = line.index("=") # will raise exception when substring is not found
74                                 curKey = line[:pos].strip()
75                                 result[curKey] = shlex.split(line[pos+1:]) # shlex.split also strips
76                         except Exception:
77                                 raise Exception("Invalid config, line %d: Error parsing line (may be a quoting issue)." % linenr)
78         # add some convencience get functions
79         return result
80
81 # Run xrandr and return a dict of output names mapped to lists of available resolutions, each being a (width, height) pair.
82 # An empty list indicates that the connector is disabled.
83 def getXrandrInformation():
84         p = subprocess.Popen(["xrandr", "-q"], stdout=subprocess.PIPE)
85         connectors = {} # map of connector names to a list of resolutions
86         connector = None # current connector
87         for line in p.stdout:
88                 # screen?
89                 m = re.search(r'^Screen [0-9]+: ', line)
90                 if m is not None: # ignore this line
91                         connector = None
92                         continue
93                 # new connector?
94                 m = re.search(r'^([\w\-]+) (dis)?connected ', line)
95                 if m is not None:
96                         connector = m.groups()[0]
97                         assert connector not in connectors
98                         connectors[connector] = []
99                         continue
100                 # new resolution?
101                 m = re.search(r'^   ([\d]+)x([\d]+) +', line)
102                 if m is not None:
103                         assert connector is not None
104                         connectors[connector].append((int(m.groups()[0]), int(m.groups()[1])))
105                         continue
106                 # unknown line
107                 # not fatal as my xrandr shows strange stuff when a display is enabled, but not connected
108                 #raise Exception("Unknown line in xrandr output:\n"+line)
109                 print "Warning: Unknown xrandr line %s" % line
110         # be sure to always proprly finish up with the xrandr
111         p.communicate()
112         # if everything succeededso far, check return code
113         if p.returncode != 0: raise Exception("Querying xrandr for data failed.")
114         return connectors
115
116 # convert a (width, height) pair into a string accepted by xrandr as argument for --mode
117 def res2xrandr(res):
118         (w, h) = res
119         return str(w)+'x'+str(h)
120
121 # convert a (width, height) pair into a string to be displayed to the user
122 def res2user(res):
123         (w, h) = res
124         # get ratio
125         ratio = int(round(16.0*h/w))
126         if ratio == 12: # 16:12 = 4:3
127                 strRatio = '4:3'
128         elif ratio == 13: # 16:12.8 = 5:4
129                 strRatio = '5:4'
130         else: # let's just hope this will never be 14 or more...
131                 strRatio = '16:%d' % ratio
132         return '%dx%d (%s)' %(w, h, strRatio)
133
134 # return the first available connector from those listed in tryConnectors, skipping disabled connectors
135 def findAvailableConnector(tryConnectors, allConnectors):
136         for connector in tryConnectors:
137                 if connector in allConnectors and allConnectors[connector]: # if the connector exists and is active (i.e. there is a resolution)
138                         return connector
139         return None
140
141 # Return a (internalConnector, externalConnectors) pair: The name of the internal connector, and a list of external connectors.
142 # Use the config file at ~/.dsl.conf and fall back to auto-detection
143 def classifyConnectors(allConnectors):
144         config = loadConfigFile(os.getenv('HOME') + '/.dsl.conf')
145         # find internal connector
146         if 'internalConnector' in config:
147                 if len(config['internalConnector']) != 1:
148                         raise Exception("You must specify exactly one internal connector.")
149                 internalConnector = config['internalConnector'][0]
150                 if not internalConnector in allConnectors:
151                         raise Exception("Connector %s does not exist, there is an error in your config file." % internalConnector)
152         else:
153                 # auto-config
154                 internalConnector = findAvailableConnector(commonInternalConnectorNames, allConnectors)
155                 if internalConnector is None:
156                         raise Exception("Could not automatically find internal connector, please use ~/.dsl.conf to specify it manually.")
157         # all the rest is external then, obviously - unless the user wants to do that manually
158         if 'externalConnectors' in config:
159                 externalConnectors = config['externalConnectors']
160                 for connector in externalConnectors:
161                         if not connector in allConnectors:
162                                 raise Exception("Connector %s does not exist, there is an error in your config file." % connector)
163                         if connector == internalConnector:
164                                 raise Exception("%s is both internal and external, that doesn't make sense." % connector)
165         else:
166                 externalConnectors = allConnectors.keys()
167                 externalConnectors.remove(internalConnector)
168         if not externalConnectors:
169                 raise Exception("No external connector found - either your config is wrong, or your machine has only one connector.")
170         # done!
171         return (internalConnector, externalConnectors)
172
173 # if we run top-level
174 if __name__ == "__main__":
175         try:
176                 # parse command-line arguments
177                 parser = argparse.ArgumentParser(description='easy Display Setup for Laptops')
178                 parser.add_argument("-r, --relative-position",
179                                                         dest="rel_position", choices=('left', 'right', 'external-only'),
180                                                         help="Position of external screen relative to internal one")
181                 cmdArgs = parser.parse_args()
182                 
183                 # load connectors and classify them
184                 connectors = getXrandrInformation()
185                 (internalConnector, externalConnectors) = classifyConnectors(connectors)
186                 
187                 # default: screen off
188                 connectorArgs = {} # maps connector names to xrand arguments
189                 for c in externalConnectors+[internalConnector]:
190                         connectorArgs[c] = ["--off"]
191                 
192                 # check whether we got an external screen or not
193                 # Check what to do
194                 usedExternalConnector = findAvailableConnector(externalConnectors, connectors) # *the* external connector which is actually used
195                 if usedExternalConnector is not None:
196                         # there's an external screen connected, we need to get a setup
197                         if cmdArgs.rel_position is not None:
198                                 # use command-line arguments (can we do this relPosition stuff more elegant?)
199                                 if cmdArgs.rel_position == 'left':
200                                         relPosition = RelativeScreenPosition.LEFT
201                                 elif cmdArgs.rel_position == 'right':
202                                         relPosition = RelativeScreenPosition.RIGHT
203                                 else:
204                                         relPosition = RelativeScreenPosition.EXTERNAL_ONLY
205                                 setup = ScreenSetup(relPosition, connectors[internalConnector][0], connectors[usedExternalConnector][0]) # use default resolutions
206                         else:
207                                 # use GUI
208                                 setup = gui.setup(connectors[internalConnector], connectors[usedExternalConnector])
209                         if setup is None: sys.exit(1) # the user canceled
210                         # apply it
211                         connectorArgs[internalConnector] = setup.getInternalArgs()
212                         connectorArgs[usedExternalConnector] = setup.getExternalArgs(internalConnector)
213                 else:
214                         # use first resolution of internal connector
215                         connectorArgs[internalConnector] = ["--mode", res2xrandr(connectors[internalConnector][0]), "--primary"]
216                 
217                 # and do it
218                 call = ["xrandr"]
219                 for name in connectorArgs:
220                         call += ["--output", name] + connectorArgs[name]
221                 print "Call that will be made:",call
222                 subprocess.check_call(call)
223         except Exception as e:
224                 gui.error(str(e))
225                 raise