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