2 # DSL - easy Display Setup for Laptops
3 # Copyright (C) 2012-2015 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.
24 # execute a process, return output as iterator, throw exception if there was an error
25 # you *must* iterate to the end if you use this!
26 def processOutputGen(*args):
27 with subprocess.Popen(args, stdout=subprocess.PIPE) as p:
29 yield line.decode("utf-8")
31 raise Exception("Error executing "+str(args))
32 def processOutputIt(*args):
33 return list(processOutputGen(*args)) # list() iterates over the generator
37 class RelativeScreenPosition(Enum):
38 '''Represents the relative position of the external screen to the internal one'''
44 def __init__(self, text):
47 self._value_ = len(cls.__members__)
52 '''Represents a resolution of a screen'''
53 def __init__(self, width, height):
57 def __eq__(self, other):
58 if not isinstance(other, Resolution):
60 return self.width == other.width and self.height == other.height
62 def __ne__(self, other):
63 return not self.__eq__(other)
67 ratio = int(round(16.0*self.height/self.width))
68 if ratio == 12: # 16:12 = 4:3
70 elif ratio == 13: # 16:12.8 = 5:4
72 else: # let's just hope this will never be 14 or more...
73 strRatio = '16:%d' % ratio
74 return '%dx%d (%s)' %(self.width, self.height, strRatio)
77 return 'screen.Resolution('+self.forXrandr()+')'
80 return str(self.width)+'x'+str(self.height)
84 '''Represents a screen configuration (relative to some notion of an "internal" and an "external" screen): Which screens are enabled with which resolution, how
85 are they positioned, which is the primary screen.'''
86 def __init__(self, intResolution, extResolution, relPosition = None, extIsPrimary = True):
87 '''The resolutions can be None to disable the screen, instances of Resolution. The last two arguments only matter if both screens are enabled.'''
88 assert intResolution is None or isinstance(intResolution, Resolution)
89 assert extResolution is None or isinstance(extResolution, Resolution)
91 self.intResolution = intResolution
92 self.extResolution = extResolution
93 self.relPosition = relPosition
94 self.extIsPrimary = extIsPrimary or self.intResolution is None # external is always primary if it is the only one
96 def getInternalArgs(self):
97 if self.intResolution is None:
99 args = ["--mode", self.intResolution.forXrandr()] # set internal screen to desired resolution
100 if not self.extIsPrimary:
101 args.append('--primary')
104 def getExternalArgs(self, intName):
105 if self.extResolution is None:
107 args = ["--mode", self.extResolution.forXrandr()] # set external screen to desired resolution
108 if self.extIsPrimary:
109 args.append('--primary')
110 if self.intResolution is None:
114 RelativeScreenPosition.LEFT : '--left-of',
115 RelativeScreenPosition.RIGHT : '--right-of',
116 RelativeScreenPosition.ABOVE : '--above',
117 RelativeScreenPosition.BELOW : '--below',
118 RelativeScreenPosition.MIRROR: '--same-as',
119 }[self.relPosition], intName]
123 class ScreenSituation:
124 connectors = {} # maps connector names to lists of Resolution (empty list -> disabled connector)
125 internalConnector = None # name of the internal connector (will be an enabled one)
126 externalConnector = None # name of the used external connector (an enabled one), or None
128 '''Represents the "screen situation" a machine can be in: Which connectors exist, which resolutions do they have, what are the names for the internal and external screen'''
129 def __init__(self, internalConnectorNames, externalConnectorNames = None):
130 '''Both arguments are lists of connector names. The first one which exists and has a screen attached is chosen for that class. <externalConnectorNames> can be None to
131 just choose any remaining connector.'''
132 # which connectors are there?
133 self._getXrandrInformation()
134 # figure out which is the internal connector
135 self.internalConnector = self._findAvailableConnector(internalConnectorNames)
136 if self.internalConnector is None:
137 raise Exception("Could not automatically find internal connector, please use (or fix) ~/.dsl.conf to specify it manually.")
138 print("Detected internal connector:",self.internalConnector)
139 # and the external one
140 if externalConnectorNames is None:
141 externalConnectorNames = list(self.connectors.keys())
142 externalConnectorNames.remove(self.internalConnector)
143 self.externalConnector = self._findAvailableConnector(externalConnectorNames)
144 if self.internalConnector == self.externalConnector:
145 raise Exception("Internal and external connector are the same. This must not happen. Please fix ~/.dsl.conf.");
146 print("Detected external connector:",self.externalConnector)
148 # Run xrandr and fill the dict of connector names mapped to lists of available resolutions.
149 def _getXrandrInformation(self):
150 connector = None # current connector
151 for line in processOutputGen("xrandr", "-q"):
153 m = re.search(r'^Screen [0-9]+: ', line)
154 if m is not None: # ignore this line
158 m = re.search(r'^([\w\-]+) (dis)?connected ', line)
160 connector = m.groups()[0]
161 assert connector not in self.connectors
162 self.connectors[connector] = []
165 m = re.search(r'^ ([\d]+)x([\d]+) +', line)
167 resolution = Resolution(int(m.groups()[0]), int(m.groups()[1]))
168 assert connector is not None
169 self.connectors[connector].append(resolution)
172 # not fatal, e.g. xrandr shows strange stuff when a display is enabled, but not connected
173 print("Warning: Unknown xrandr line %s" % line)
175 # return the first available connector from those listed in <tryConnectors>, skipping disabled connectors
176 def _findAvailableConnector(self, tryConnectors):
177 for connector in tryConnectors:
178 if connector in self.connectors and len(self.connectors[connector]): # if the connector exists and is active (i.e. there is a resolution)
182 # return available internal resolutions
183 def internalResolutions(self):
184 return self.connectors[self.internalConnector]
186 # return available external resolutions (or None, if there is no external screen connected)
187 def externalResolutions(self):
188 if self.externalConnector is None:
190 return self.connectors[self.externalConnector]
192 # return resolutions available for both internal and external screen
193 def commonResolutions(self):
194 internalRes = self.internalResolutions()
195 externalRes = self.externalResolutions()
196 assert externalRes is not None
197 return [res for res in externalRes if res in internalRes]
199 # compute the xrandr call
200 def forXrandr(self, setup):
201 # turn all screens off
202 connectorArgs = {} # maps connector names to xrand arguments
203 for c in self.connectors.keys():
204 connectorArgs[c] = ["--off"]
205 # set arguments for the relevant ones
206 connectorArgs[self.internalConnector] = setup.getInternalArgs()
207 if self.externalConnector is not None:
208 connectorArgs[self.externalConnector] = setup.getExternalArgs(self.internalConnector)
210 assert setup.extResolution is None, "There's no external screen to set a resolution for"
211 # now compose the arguments
213 for name in connectorArgs:
214 call += ["--output", name] + connectorArgs[name]