Merge branch 'master' of git://ralfj.de/dsl
[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         connector = None # current connector
53         for line in p.stdout:
54                 # ignore screens
55                 if line.startswith("Screen"):
56                         continue
57                 # new connector?
58                 m = re.search(r'^([\w\-]+) (dis)?connected ', line)
59                 if m is not None:
60                         connector = m.groups()[0]
61                         assert connector not in connectors
62                         connectors[connector] = []
63                         continue
64                 # new resolution?
65                 m = re.search(r'^   ([\d]+)x([\d]+) +', line)
66                 if m is not None:
67                         assert connector is not None
68                         connectors[connector].append((int(m.groups()[0]), int(m.groups()[1])))
69         p.communicate()
70         if p.returncode != 0: raise Exception("Querying xrandr for data failed.")
71         return connectors
72
73 def res2xrandr(res):
74         (w, h) = res
75         return str(w)+'x'+str(h)
76
77 def res2user(res):
78         (w, h) = res
79         # get ratio
80         ratio = int(round(16.0*h/w))
81         if ratio == 12: # 16:12 = 4:3
82                 strRatio = '4:3'
83         elif ratio == 13: # 16:12.8 = 5:4
84                 strRatio = '5:4'
85         else: # let's just hope this will never be 14 or more...
86                 strRatio = '16:%d' % ratio
87         return '%dx%d (%s)' %(w, h, strRatio)
88
89 def findAvailableConnector(tryConnectors):
90         for connector in tryConnectors:
91                 if connector in connectors and connectors[connector]: # if the connector exists and is active (i.e. there is a resolution)
92                         return connector
93         return None
94
95 # the main function
96 def main():
97         # load connectors and options
98         connectors = getXrandrInformation()
99         config = loadConfigFile(os.getenv('HOME') + '/.dsl.conf')
100         # find internal connector
101         if 'internalConnector' in config:
102                 if len(config['internalConnector']) != 1:
103                         raise Exception("You must specify exactly one internal connector.")
104                 internalConnector = config['internalConnector'][0]
105                 if not internalConnector in connectors:
106                         raise Exception("Connector %s does not exist, there is an error in your config file." % internalConnector)
107         else:
108                 # auto-config
109                 internalConnector = findAvailableConnector(commonInternalConnectorNames)
110                 if internalConnector is None:
111                         raise Exception("Could not automatically find internal connector, please use ~/.dsl.conf to specify it manually.")
112         # all the rest is external then, obviously - unless the user wants to do that manually
113         if 'externalConnectors' in config:
114                 externalConnectors = config['externalConnectors']
115                 for connector in externalConnectors:
116                         if not connector in connectors:
117                                 raise Exception("Connector %s does not exist, there is an error in your config file." % internalConnector)
118         else:
119                 externalConnectors = connectors.keys()
120                 externalConnectors.remove(internalConnector)
121         if not externalConnectors:
122                 raise Exception("No external connector found - either your config is wrong, or your machine has only one connector.")
123
124         # default: screen off
125         args = {} # maps connector names to xrand arguments
126         for c in externalConnectors+[internalConnector]:
127                 args[c] = ["--off"]
128
129         # Check what to do
130         usedExternalConnector = findAvailableConnector(externalConnectors) # *the* external connector which is actually used
131         if usedExternalConnector is not None: # there's an external screen connected, we need to ask what to do
132                 internalResolutions = connectors[internalConnector]
133                 externalResolutions = connectors[usedExternalConnector]
134                 extPosition = PositionSelection(usedExternalConnector, map(res2user, internalResolutions), map(res2user, externalResolutions))
135                 extPosition.exec_()
136                 if not extPosition.result(): sys.exit(1) # the user canceled
137                 extResolution = res2xrandr(externalResolutions[extPosition.extResolutions.currentIndex()])
138                 intResolution = res2xrandr(internalResolutions[extPosition.intResolutions.currentIndex()])
139                 # build command-line
140                 args[usedExternalConnector] = ["--mode", extResolution] # set external screen to desired resolution
141                 if extPosition.extOnly.isChecked():
142                         args[usedExternalConnector] += ["--primary"]
143                 else:
144                         # there are two screens
145                         args[internalConnector] = ["--mode", intResolution] # set internal screen to desired resolution
146                         # set position
147                         if extPosition.posLeft.isChecked():
148                                 args[usedExternalConnector] += ["--left-of", internalConnector]
149                         else:
150                                 args[usedExternalConnector] += ["--right-of", internalConnector]
151                         # set primary screen
152                         if extPosition.primExt.isChecked():
153                                 args[usedExternalConnector] += ["--primary"]
154                         else:
155                                 args[internalConnector] += ["--primary"]
156         else:
157                 # use first resolution
158                 args[internalConnector] = ["--mode", res2xrandr(connectors[internalConnector][0]), "--primary"]
159         # and do it
160         call = ["xrandr"]
161         for name in args:
162                 call += ["--output", name] + args[name]
163         print "Call that will be made:",call
164         subprocess.check_call(call)
165
166 # if we run top-level
167 if __name__ == "__main__":
168         try:
169                 main()
170         except Exception as e:
171                 gui.error(str(e))
172                 raise