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