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