use a config file instead of hard-coding connector names
[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 # Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
10 def loadConfigFile(file):
11         import shlex
12         # read config file
13         linenr = 0
14         with open(file) as file:
15                 result = {}
16                 for line in file:
17                         linenr += 1
18                         line = line.strip()
19                         if not len(line) or line.startswith("#"): continue # skip empty and comment lines
20                         try:
21                                 # parse line
22                                 pos = line.index("=") # will raise exception when substring is not found
23                                 curKey = line[:pos].strip()
24                                 value = line[pos+1:]
25                                 result[curKey] = shlex.split(value)
26                         except Exception:
27                                 raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)" % linenr)
28         # add some convencience get functions
29         return result
30
31 def getXrandrInformation():
32         p = subprocess.Popen(["xrandr", "-q"], stdout=subprocess.PIPE)
33         connectors = {} # map of connector names to a list of resolutions
34         connector = None # current connector
35         for line in p.stdout:
36                 # new connector?
37                 m = re.search(r'^([\w]+) connected ', line)
38                 if m is not None:
39                         connector = m.groups()[0]
40                         assert connector not in connectors
41                         connectors[connector] = []
42                         continue
43                 # new resolution?
44                 m = re.search(r'^   ([\d]+)x([\d]+) +', line)
45                 if m is not None:
46                         assert connector is not None
47                         connectors[connector].append((int(m.groups()[0]), int(m.groups()[1])))
48         p.communicate()
49         if p.returncode != 0: raise Exception("Querying xrandr for data failed")
50         return connectors
51
52 def res2xrandr(res):
53         (w, h) = res
54         return str(w)+'x'+str(h)
55
56 def res2user(res):
57         (w, h) = res
58         # get ratio
59         ratio = int(round(16.0*h/w))
60         if ratio == 12: # 16:12 = 4:3
61                 strRatio = '4:3'
62         elif ratio == 13: # 16:12.8 = 5:4
63                 strRatio = '5:4'
64         else: # let's just hope this will never be 14 or more...
65                 strRatio = '16:%d' % ratio
66         return '%dx%d (%s)' %(w, h, strRatio)
67
68 def findAvailableConnector(tryConnectors, availableConnectors):
69         for connector in tryConnectors:
70                 if connector in availableConnectors: return connector
71         return None
72
73 # load options
74 config = loadConfigFile(os.getenv('HOME') + '/.dsl.conf')
75 if len(config['internalConnector']) != 1:
76         raise Exception("You must specify exactly one internal connector")
77 if len(config['externalConnectors']) < 1:
78         raise Exception("You must specify at least one external connector")
79 # use options
80 internalConnector = config['internalConnector'][0]
81 externalConnectors = config['externalConnectors']
82 connectors = getXrandrInformation()
83 usedExternalConnector = findAvailableConnector(externalConnectors, connectors) # *the* external connector which is actually used
84
85 # default: screen off
86 args = {} # maps connector names to xrand arguments
87 for c in externalConnectors+[internalConnector]:
88         args[c] = ["--off"]
89
90 # Check what to do
91 if usedExternalConnector is not None: # there's an external screen connected, we need to ask what to do
92         internalResolutions = connectors[internalConnector]
93         externalResolutions = connectors[usedExternalConnector]
94         extPosition = PositionSelection(usedExternalConnector, map(res2user, internalResolutions), map(res2user, externalResolutions))
95         extPosition.exec_()
96         if not extPosition.result(): sys.exit(1) # the user canceled
97         extResolution = res2xrandr(externalResolutions[extPosition.extResolutions.currentIndex()])
98         intResolution = res2xrandr(internalResolutions[extPosition.intResolutions.currentIndex()])
99         # build command-line
100         args[usedExternalConnector] = ["--mode", extResolution] # set external screen to desired resolution
101         if extPosition.extOnly.isChecked():
102                 args[usedExternalConnector] += ["--primary"]
103         else:
104                 # there are two screens
105                 args[internalConnector] = ["--mode", intResolution] # set internal screen to desired resolution
106                 # set position
107                 if extPosition.posLeft.isChecked():
108                         args[usedExternalConnector] += ["--left-of", internalConnector]
109                 else:
110                         args[usedExternalConnector] += ["--right-of", internalConnector]
111                 # set primary screen
112                 if extPosition.primExt.isChecked():
113                         args[usedExternalConnector] += ["--primary"]
114                 else:
115                         args[internalConnector] += ["--primary"]
116 else:
117         # use first resolution
118         args[internalConnector] = ["--mode", res2xrandr(connectors[internalConnector][0]), "--primary"]
119 # and do it
120 call = ["xrandr"]
121 for name in args:
122         call += ["--output", name] + args[name]
123 print "Call that will be made:",call
124 subprocess.check_call(call)