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