convert DSL to Python3 (just ran 2to3)
[lilass.git] / dsl.py
1 #!/usr/bin/python3
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; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
19 import argparse, sys, os, re, subprocess
20 from gui import getFrontend
21 frontend = getFrontend("cli") # the fallback, until we got a proper frontend. This is guaranteed to be available.
22
23 # for auto-config: common names of internal connectors
24 commonInternalConnectorNames = ['LVDS', 'LVDS0', 'LVDS1', 'LVDS-0', 'LVDS-1']
25
26 # this is as close as one can get to an enum in Python
27 class RelativeScreenPosition:
28         LEFT          = 0
29         RIGHT         = 1
30         EXTERNAL_ONLY = 2
31
32 # storing what's necessary for screen setup
33 class ScreenSetup:
34         def __init__(self, relPosition, intResolution, extResolution, extIsPrimary = False):
35                 '''relPosition must be one of the RelativeScreenPosition members, the resolutions must be (width, height) pairs'''
36                 self.relPosition = relPosition
37                 self.intResolution = intResolution # value doesn't matter if the internal screen is disabled
38                 self.extResolution = extResolution
39                 self.extIsPrimary = extIsPrimary or self.relPosition == RelativeScreenPosition.EXTERNAL_ONLY # external is always primary if it is the only one
40         
41         def getInternalArgs(self):
42                 if self.relPosition == RelativeScreenPosition.EXTERNAL_ONLY:
43                         return ["--off"]
44                 args = ["--mode", res2xrandr(self.intResolution)] # set internal screen to desired resolution
45                 if not self.extIsPrimary:
46                         args.append('--primary')
47                 return args
48         
49         def getExternalArgs(self, intName):
50                 args = ["--mode", res2xrandr(self.extResolution)] # set external screen to desired resolution
51                 if self.extIsPrimary:
52                         args.append('--primary')
53                 if self.relPosition == RelativeScreenPosition.LEFT:
54                         args += ['--left-of', intName]
55                 elif self.relPosition == RelativeScreenPosition.RIGHT:
56                         args += ['--right-of', intName]
57                 return args
58
59 # Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
60 def loadConfigFile(file):
61         import shlex
62         result = {}
63         if not os.path.exists(file):
64                 return result # no config file
65         # read config file
66         linenr = 0
67         with open(file) as file:
68                 for line in file:
69                         linenr += 1
70                         line = line.strip()
71                         if not len(line) or line.startswith("#"): continue # skip empty and comment lines
72                         try:
73                                 # parse line
74                                 pos = line.index("=") # will raise exception when substring is not found
75                                 curKey = line[:pos].strip()
76                                 result[curKey] = shlex.split(line[pos+1:]) # shlex.split also strips
77                         except Exception:
78                                 raise Exception("Invalid config, line %d: Error parsing line (may be a quoting issue)." % linenr)
79         # add some convencience get functions
80         return result
81
82 # helper function: execute a process, return output as iterator, throw exception if there was an error
83 # you *must* iterate to the end if you use this!
84 def processOutputGen(*args):
85         p = subprocess.Popen(args, stdout=subprocess.PIPE)
86         for line in p.stdout:
87                 yield line
88         p.wait() # wait for process to exit (it closed stdout, so it can't block anymore)
89         if p.returncode != 0:
90                 raise Exception("Error executing "+str(args))
91 def processOutputIt(*args):
92         return list(processOutputGen(*args)) # list() iterates over the generator
93
94 # Run xrandr and return a dict of output names mapped to lists of available resolutions, each being a (width, height) pair.
95 # An empty list indicates that the connector is disabled.
96 def getXrandrInformation():
97         connectors = {} # map of connector names to a list of resolutions
98         connector = None # current connector
99         for line in processOutputGen("xrandr", "-q"):
100                 # screen?
101                 m = re.search(r'^Screen [0-9]+: ', line)
102                 if m is not None: # ignore this line
103                         connector = None
104                         continue
105                 # new connector?
106                 m = re.search(r'^([\w\-]+) (dis)?connected ', line)
107                 if m is not None:
108                         connector = m.groups()[0]
109                         assert connector not in connectors
110                         connectors[connector] = []
111                         continue
112                 # new resolution?
113                 m = re.search(r'^   ([\d]+)x([\d]+) +', line)
114                 if m is not None:
115                         assert connector is not None
116                         connectors[connector].append((int(m.groups()[0]), int(m.groups()[1])))
117                         continue
118                 # unknown line
119                 # not fatal as my xrandr shows strange stuff when a display is enabled, but not connected
120                 #raise Exception("Unknown line in xrandr output:\n"+line)
121                 print("Warning: Unknown xrandr line %s" % line)
122         return connectors
123
124 # convert a (width, height) pair into a string accepted by xrandr as argument for --mode
125 def res2xrandr(res):
126         (w, h) = res
127         return str(w)+'x'+str(h)
128
129 # convert a (width, height) pair into a string to be displayed to the user
130 def res2user(res):
131         (w, h) = res
132         # get ratio
133         ratio = int(round(16.0*h/w))
134         if ratio == 12: # 16:12 = 4:3
135                 strRatio = '4:3'
136         elif ratio == 13: # 16:12.8 = 5:4
137                 strRatio = '5:4'
138         else: # let's just hope this will never be 14 or more...
139                 strRatio = '16:%d' % ratio
140         return '%dx%d (%s)' %(w, h, strRatio)
141
142 # return the first available connector from those listed in tryConnectors, skipping disabled connectors
143 def findAvailableConnector(tryConnectors, allConnectors):
144         for connector in tryConnectors:
145                 if connector in allConnectors and allConnectors[connector]: # if the connector exists and is active (i.e. there is a resolution)
146                         return connector
147         return None
148
149 # Return a (internalConnector, externalConnectors) pair: The name of the internal connector, and a list of external connectors.
150 # Use the config file at ~/.dsl.conf and fall back to auto-detection
151 def classifyConnectors(allConnectors):
152         config = loadConfigFile(os.getenv('HOME') + '/.dsl.conf')
153         # find internal connector
154         if 'internalConnector' in config:
155                 if len(config['internalConnector']) != 1:
156                         raise Exception("You must specify exactly one internal connector.")
157                 internalConnector = config['internalConnector'][0]
158                 if not internalConnector in allConnectors:
159                         raise Exception("Connector %s does not exist, there is an error in your config file." % internalConnector)
160         else:
161                 # auto-config
162                 internalConnector = findAvailableConnector(commonInternalConnectorNames, allConnectors)
163                 if internalConnector is None:
164                         raise Exception("Could not automatically find internal connector, please use ~/.dsl.conf to specify it manually.")
165         # all the rest is external then, obviously - unless the user wants to do that manually
166         if 'externalConnectors' in config:
167                 externalConnectors = config['externalConnectors']
168                 for connector in externalConnectors:
169                         if not connector in allConnectors:
170                                 raise Exception("Connector %s does not exist, there is an error in your config file." % connector)
171                         if connector == internalConnector:
172                                 raise Exception("%s is both internal and external, that doesn't make sense." % connector)
173         else:
174                 externalConnectors = list(allConnectors.keys())
175                 externalConnectors.remove(internalConnector)
176         if not externalConnectors:
177                 raise Exception("No external connector found - either your config is wrong, or your machine has only one connector.")
178         # done!
179         return (internalConnector, externalConnectors)
180
181 # if we run top-level
182 if __name__ == "__main__":
183         try:
184                 # parse command-line arguments
185                 parser = argparse.ArgumentParser(description='easy Display Setup for Laptops')
186                 parser.add_argument("-f, --frontend",
187                                                         dest="frontend",
188                                                         help="The frontend to be used for user interaction")
189                 parser.add_argument("-r, --relative-position",
190                                                         dest="rel_position", choices=('left', 'right', 'external-only'),
191                                                         help="Position of external screen relative to internal one")
192                 cmdArgs = parser.parse_args()
193                 
194                 # load frontend
195                 frontend = getFrontend(cmdArgs.frontend)
196                 
197                 # load connectors and classify them
198                 connectors = getXrandrInformation()
199                 (internalConnector, externalConnectors) = classifyConnectors(connectors)
200                 
201                 # default: screen off
202                 connectorArgs = {} # maps connector names to xrand arguments
203                 for c in externalConnectors+[internalConnector]:
204                         connectorArgs[c] = ["--off"]
205                 
206                 # check whether we got an external screen or not
207                 # Check what to do
208                 usedExternalConnector = findAvailableConnector(externalConnectors, connectors) # *the* external connector which is actually used
209                 if usedExternalConnector is not None:
210                         # there's an external screen connected, we need to get a setup
211                         if cmdArgs.rel_position is not None:
212                                 # use command-line arguments (can we do this relPosition stuff more elegant?)
213                                 if cmdArgs.rel_position == 'left':
214                                         relPosition = RelativeScreenPosition.LEFT
215                                 elif cmdArgs.rel_position == 'right':
216                                         relPosition = RelativeScreenPosition.RIGHT
217                                 else:
218                                         relPosition = RelativeScreenPosition.EXTERNAL_ONLY
219                                 setup = ScreenSetup(relPosition, connectors[internalConnector][0], connectors[usedExternalConnector][0]) # use default resolutions
220                         else:
221                                 # use GUI
222                                 setup = frontend.setup(connectors[internalConnector], connectors[usedExternalConnector])
223                         if setup is None: sys.exit(1) # the user canceled
224                         # apply it
225                         connectorArgs[internalConnector] = setup.getInternalArgs()
226                         connectorArgs[usedExternalConnector] = setup.getExternalArgs(internalConnector)
227                 else:
228                         # use first resolution of internal connector
229                         connectorArgs[internalConnector] = ["--mode", res2xrandr(connectors[internalConnector][0]), "--primary"]
230                 
231                 # and do it
232                 call = ["xrandr"]
233                 for name in connectorArgs:
234                         call += ["--output", name] + connectorArgs[name]
235                 print("Call that will be made:",call)
236                 subprocess.check_call(call)
237         except Exception as e:
238                 frontend.error(str(e))
239                 raise