Merge pull request #4 from ConnyOnny/master
[lilass.git] / lilass
1 #!/usr/bin/env python3
2 # DSL - easy Display Setup for Laptops
3 # Copyright (C) 2012-2015 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, os.path, shutil, re, subprocess
20 from enum import Enum
21 import gui, screen, util, database
22 frontend = gui.getFrontend("cli") # the fallback, until we got a proper frontend. This is guaranteed to be available.
23 cmdArgs = None
24
25 # for auto-config: common names of internal connectors
26 commonInternalConnectorPrefixes = ['LVDS', 'eDP']
27 commonInternalConnectorSuffices = ['', '0', '1', '-0', '-1']
28 def commonInternalConnectorNames():
29     for prefix in commonInternalConnectorPrefixes:
30         for suffix in commonInternalConnectorSuffices:
31             yield prefix+suffix
32
33 # Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
34 def loadConfigFile(filename):
35     import shlex
36     result = {}
37     if not os.path.exists(filename):
38         return result # no config file
39     # read config file
40     linenr = 0
41     with open(filename) as f:
42         for line in f:
43             linenr += 1
44             line = line.strip()
45             if not len(line) or line.startswith("#"): continue # skip empty and comment lines
46             try:
47                 # parse line
48                 pos = line.index("=") # will raise exception when substring is not found
49                 curKey = line[:pos].strip()
50                 result[curKey] = shlex.split(line[pos+1:]) # shlex.split also strips
51             except Exception:
52                 raise Exception("Invalid config, line %d: Error parsing line (may be a quoting issue)." % linenr)
53     # add some convencience get functions
54     return result
55
56
57 # Make sure the backlight is turned on
58 def turnOnBacklight():
59     try:
60         backlight = float(subprocess.check_output(["xbacklight", "-get"]).strip())
61         if backlight == 0: # it's completely turned off, we better enable it
62             subprocess.check_call(["xbacklight", "-set", "100"])
63     except FileNotFoundError:
64         print("xbacklight has not been found, unable to turn your laptop backlight on.")
65     except subprocess.CalledProcessError:
66         print("xbacklight returned an error while attempting to turn your laptop backlight on.")
67
68
69 # return the current sceen situation, using the configuration to control connecor detection
70 def situationByConfig(config):
71     # internal connectors
72     if 'internalConnector' in config:
73         if len(config['internalConnector']) != 1:
74             raise Exception("You must specify exactly one internal connector.")
75         internalConnectors = config['internalConnector']
76     else:
77         internalConnectors = commonInternalConnectorNames()
78     # run!
79     return screen.ScreenSituation(internalConnectors, config.get('externalConnectors'))
80
81 # if we run top-level
82 if __name__ == "__main__":
83     try:
84         # how do we filter the RelativeScreenPosition for the CLI?
85         relPosFilter = str.lower
86         
87         # parse command-line arguments
88         parser = argparse.ArgumentParser(description='easy Display Setup for Laptops')
89         parser.add_argument("-f", "--frontend",
90                             dest="frontend",
91                             help="The frontend to be used for user interaction")
92         parser.add_argument("-r", "--relative-position",
93                             dest="rel_position", choices=list(map(relPosFilter, screen.RelativeScreenPosition.__members__.keys())),
94                             help="Set the position of external screen relative to internal one, in case it is not found in the DB.")
95         parser.add_argument("-e", "--external-only",
96                             dest="external_only", action='store_true',
97                             help="If an external screen is connected, disable all the others.")
98         parser.add_argument("-i", "--internal-only",
99                             dest="internal_only", action='store_true',
100                             help="Enable internal screen, disable all the others.")
101         parser.add_argument("-s", "--silent",
102                             dest="silent", action='store_true',
103                             help="Prefer to be silent: Opens a UI only if the external screen is not known *and* no default configuration (-r/-e/-i) is given.")
104         parser.add_argument("--no-db",
105                             dest="use_db", action='store_false',
106                             help="Do not use the database of known screens.")
107         parser.add_argument("-v", "--verbose",
108                             dest="verbose", action='store_true',
109                             help="More verbose output on stderr.")
110         cmdArgs = parser.parse_args()
111     
112         # load frontend early (for error mssages)
113         frontend = gui.getFrontend(cmdArgs.frontend)
114         
115         # find files
116         ## find config file
117         legacyConfigFilePath = os.getenv('HOME') + '/.lilass.conf'
118         configDirectory = util.getConfigDirectory()
119         configFilePath = os.path.join(configDirectory, "lilass.conf")
120         if os.path.isfile(legacyConfigFilePath) and not os.path.isfile(configFilePath):
121             # looks like we just upgraded to a new version of lilass
122             util.mkdirP(configDirectory)
123             shutil.move(legacyConfigFilePath, configFilePath)
124         ## find database
125         dataDirectory = util.getDataDirectory()
126         util.mkdirP(dataDirectory)
127         databaseFilePath = os.path.join(dataDirectory, "collected_data.sqlite")
128
129         # load configuration
130         config = loadConfigFile(configFilePath)
131         
132         # see what situation we are in
133         situation = situationByConfig(config)
134         
135         # construct the ScreenSetup
136         setup = None
137         if situation.externalConnector is not None:
138             # There's an external screen connected that we may want to use.
139             # Fetch info about this screen from the database.
140             # NOTE: If it is too slow to open the DB twice (reading and saving), we can keep it open all the time
141             if cmdArgs.use_db:
142                 with database.Database(databaseFilePath) as db:
143                     situation.fetchDBInfo(db)
144             # what to we do?
145             have_default_conf = bool(cmdArgs.external_only or cmdArgs.internal_only or cmdArgs.rel_position)
146             no_ui = bool(have_default_conf or (situation.previousSetup and cmdArgs.silent))
147             if not no_ui:
148                 # ask the user what to do
149                 setup = frontend.setup(situation)
150                 if setup is None: sys.exit(1) # the user canceled
151                 if cmdArgs.use_db:
152                     # persists this to disk
153                     with database.Database(databaseFilePath) as db:
154                         situation.putDBInfo(db, setup)
155             elif situation.previousSetup:
156                 # apply the old setup again
157                 setup = situation.previousSetup
158             # use default config from CLI
159             elif cmdArgs.external_only:
160                 setup = screen.ScreenSetup(intResolution = None, extResolution = situation.externalConnector.getPreferredResolution())
161             elif cmdArgs.rel_position is not None:
162                 # construct automatically, based on CLI arguments
163                 # first, figure out the desired RelativeScreenPosition... waht a bad hack...
164                 relPos = list(filter(lambda relPosItem: relPosFilter(relPosItem[0]) == cmdArgs.rel_position, screen.RelativeScreenPosition.__members__.items()))
165                 assert len(relPos) == 1, "CLI argument is ambigue"
166                 relPos = relPos[0][1]
167                 # now we construct the ScreenSetup
168                 if relPos == screen.RelativeScreenPosition.MIRROR:
169                     res = situation.commonResolutions()[0]
170                     setup = screen.ScreenSetup(res, res, relPos)
171                 else:
172                     setup = screen.ScreenSetup(intResolution = situation.internalConnector.getPreferredResolution(),
173                                                extResolution = situation.externalConnector.getPreferredResolution(),
174                                                relPosition = relPos)
175             # cmdArgs.internal_only: fall-through
176         if setup is None:
177             assert cmdArgs.internal_only or situation.externalConnector is None
178             # Nothing chosen yet? Use first resolution of internal connector.
179             setup = screen.ScreenSetup(intResolution = situation.internalConnector.getPreferredResolution(), extResolution = None)
180         
181         # call xrandr
182         xrandrCall = situation.forXrandr(setup)
183         print("Call that will be made:",xrandrCall)
184         subprocess.check_call(xrandrCall)
185         
186         # make sure the internal screen is really, *really* turned on if there is no external screen
187         if setup.extResolution is None:
188             turnOnBacklight()
189     except Exception as e:
190         frontend.error(str(e))
191         if cmdArgs is None or cmdArgs.verbose:
192             raise(e)