0704d3e8f3da546f9b5e510976cf98bcbebe328a
[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 os, re, subprocess
20 from selector_window import PositionSelection
21 import gui
22
23 # for auto-config: common names of internal connectors
24 commonInternalConnectorNames = ['LVDS', 'LVDS0', 'LVDS1', 'LVDS-0', 'LVDS-1']
25
26 # Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
27 def loadConfigFile(file):
28         import shlex
29         result = {}
30         if not os.path.exists(file):
31                 return result # no config file
32         # read config file
33         linenr = 0
34         with open(file) as file:
35                 for line in file:
36                         linenr += 1
37                         line = line.strip()
38                         if not len(line) or line.startswith("#"): continue # skip empty and comment lines
39                         try:
40                                 # parse line
41                                 pos = line.index("=") # will raise exception when substring is not found
42                                 curKey = line[:pos].strip()
43                                 result[curKey] = shlex.split(line[pos+1:]) # shlex.split also strips
44                         except Exception:
45                                 raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)." % linenr)
46         # add some convencience get functions
47         return result
48
49 def getXrandrInformation():
50         p = subprocess.Popen(["xrandr", "-q"], stdout=subprocess.PIPE)
51         connectors = {} # map of connector names to a list of resolutions
52         try:
53                 connector = None # current connector
54                 for line in p.stdout:
55                         # screen?
56                         m = re.search(r'^Screen [0-9]+: ', line)
57                         if m is not None: # ignore this line
58                                 connector = None
59                                 continue
60                         # new connector?
61                         m = re.search(r'^([\w\-]+) (dis)?connected ', line)
62                         if m is not None:
63                                 connector = m.groups()[0]
64                                 assert connector not in connectors
65                                 connectors[connector] = []
66                                 continue
67                         # new resolution?
68                         m = re.search(r'^   ([\d]+)x([\d]+) +', line)
69                         if m is not None:
70                                 assert connector is not None
71                                 connectors[connector].append((int(m.groups()[0]), int(m.groups()[1])))
72                                 continue
73                         # unknown line
74                         raise Exception("Unknown line in xrandr output:\n"+line)
75         finally:
76                 # be sure to always proprly finish up with the xrandr
77                 p.communicate()
78         # if everything succeededso far, check return code
79         if p.returncode != 0: raise Exception("Querying xrandr for data failed.")
80         return connectors
81
82 def res2xrandr(res):
83         (w, h) = res
84         return str(w)+'x'+str(h)
85
86 def res2user(res):
87         (w, h) = res
88         # get ratio
89         ratio = int(round(16.0*h/w))
90         if ratio == 12: # 16:12 = 4:3
91                 strRatio = '4:3'
92         elif ratio == 13: # 16:12.8 = 5:4
93                 strRatio = '5:4'
94         else: # let's just hope this will never be 14 or more...
95                 strRatio = '16:%d' % ratio
96         return '%dx%d (%s)' %(w, h, strRatio)
97
98 def findAvailableConnector(tryConnectors, allConnectors):
99         for connector in tryConnectors:
100                 if connector in allConnectors and allConnectors[connector]: # if the connector exists and is active (i.e. there is a resolution)
101                         return connector
102         return None
103
104 # the main function
105 def main():
106         # load connectors and options
107         connectors = getXrandrInformation()
108         config = loadConfigFile(os.getenv('HOME') + '/.dsl.conf')
109         # find internal connector
110         if 'internalConnector' in config:
111                 if len(config['internalConnector']) != 1:
112                         raise Exception("You must specify exactly one internal connector.")
113                 internalConnector = config['internalConnector'][0]
114                 if not internalConnector in connectors:
115                         raise Exception("Connector %s does not exist, there is an error in your config file." % internalConnector)
116         else:
117                 # auto-config
118                 internalConnector = findAvailableConnector(commonInternalConnectorNames, connectors)
119                 if internalConnector is None:
120                         raise Exception("Could not automatically find internal connector, please use ~/.dsl.conf to specify it manually.")
121         # all the rest is external then, obviously - unless the user wants to do that manually
122         if 'externalConnectors' in config:
123                 externalConnectors = config['externalConnectors']
124                 for connector in externalConnectors:
125                         if not connector in connectors:
126                                 raise Exception("Connector %s does not exist, there is an error in your config file." % internalConnector)
127         else:
128                 externalConnectors = connectors.keys()
129                 externalConnectors.remove(internalConnector)
130         if not externalConnectors:
131                 raise Exception("No external connector found - either your config is wrong, or your machine has only one connector.")
132
133         # default: screen off
134         args = {} # maps connector names to xrand arguments
135         for c in externalConnectors+[internalConnector]:
136                 args[c] = ["--off"]
137
138         # Check what to do
139         usedExternalConnector = findAvailableConnector(externalConnectors, connectors) # *the* external connector which is actually used
140         if usedExternalConnector is not None: # there's an external screen connected, we need to ask what to do
141                 internalResolutions = connectors[internalConnector]
142                 externalResolutions = connectors[usedExternalConnector]
143                 extPosition = PositionSelection(usedExternalConnector, map(res2user, internalResolutions), map(res2user, externalResolutions))
144                 extPosition.exec_()
145                 if not extPosition.result(): sys.exit(1) # the user canceled
146                 extResolution = res2xrandr(externalResolutions[extPosition.extResolutions.currentIndex()])
147                 intResolution = res2xrandr(internalResolutions[extPosition.intResolutions.currentIndex()])
148                 # build command-line
149                 args[usedExternalConnector] = ["--mode", extResolution] # set external screen to desired resolution
150                 if extPosition.extOnly.isChecked():
151                         args[usedExternalConnector] += ["--primary"]
152                 else:
153                         # there are two screens
154                         args[internalConnector] = ["--mode", intResolution] # set internal screen to desired resolution
155                         # set position
156                         if extPosition.posLeft.isChecked():
157                                 args[usedExternalConnector] += ["--left-of", internalConnector]
158                         else:
159                                 args[usedExternalConnector] += ["--right-of", internalConnector]
160                         # set primary screen
161                         if extPosition.primExt.isChecked():
162                                 args[usedExternalConnector] += ["--primary"]
163                         else:
164                                 args[internalConnector] += ["--primary"]
165         else:
166                 # use first resolution
167                 args[internalConnector] = ["--mode", res2xrandr(connectors[internalConnector][0]), "--primary"]
168         # and do it
169         call = ["xrandr"]
170         for name in args:
171                 call += ["--output", name] + args[name]
172         print "Call that will be made:",call
173         subprocess.check_call(call)
174
175 # if we run top-level
176 if __name__ == "__main__":
177         try:
178                 main()
179         except Exception as e:
180                 gui.error(str(e))
181                 raise