]> git.donarmstrong.com Git - deb_pkgs/autorandr.git/blobdiff - autorandr.py
Python: Python 3 compatibility restored
[deb_pkgs/autorandr.git] / autorandr.py
index 4c75f1d27fe07a9506f2944b4747f778c9202fc5..1225491d9fc492923159a817d7b026ee142a11bc 100755 (executable)
@@ -32,6 +32,7 @@ import os
 import re
 import subprocess
 import sys
+from distutils.version import LooseVersion as Version
 
 from itertools import chain
 from collections import OrderedDict
@@ -112,10 +113,29 @@ class XrandrOutput(object):
     def __repr__(self):
         return "<%s%s %s>" % (self.output, (" %s..%s" % (self.edid[:5], self.edid[-5:])) if self.edid else "", " ".join(self.option_vector))
 
+    @property
+    def options_with_defaults(self):
+        "Return the options dictionary, augmented with the default values that weren't set"
+        if "off" in self.options:
+            return self.options
+        options = {}
+        if xrandr_version() >= Version("1.3"):
+            options.update({
+                "transform": "1,0,0,0,1,0,0,0,1",
+            })
+        if xrandr_version() >= Version("1.2"):
+            options.update({
+                "reflect": "normal",
+                "rotate": "normal",
+                "gamma": "1:1:1",
+            })
+        options.update(self.options)
+        return options
+
     @property
     def option_vector(self):
         "Return the command line parameters for XRandR for this instance"
-        return sum([["--%s" % option[0], option[1]] if option[1] else ["--%s" % option[0]] for option in chain((("output", self.output),), self.options.items())], [])
+        return sum([["--%s" % option[0], option[1]] if option[1] else ["--%s" % option[0]] for option in chain((("output", self.output),), self.options_with_defaults.items())], [])
 
     @property
     def option_string(self):
@@ -175,8 +195,8 @@ class XrandrOutput(object):
                 options["mode"] = "%sx%s" % (match["width"], match["height"])
             else:
                 options["mode"] = "%sx%s" % (match["height"], match["width"])
-            options["rotate"] = match["rotate"]
-            options["reflect"] = "normal"
+            if match["rotate"] != "normal":
+                options["rotate"] = match["rotate"]
             if "reflect" in match:
                 if match["reflect"] == "X":
                     options["reflect"] = "x"
@@ -189,8 +209,6 @@ class XrandrOutput(object):
                 transformation = ",".join(match["transform"].strip().split())
                 if transformation != "1.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,1.000000":
                     options["transform"] = transformation
-                else:
-                    options["transform"] = "none"
             if match["gamma"]:
                 gamma = match["gamma"].strip()
                 if gamma != "1.0:1.0:1.0":
@@ -237,6 +255,14 @@ class XrandrOutput(object):
     def __eq__(self, other):
         return self.edid == other.edid and self.output == other.output and self.options == other.options
 
+def xrandr_version():
+    "Return the version of XRandR that this system uses"
+    if getattr(xrandr_version, "version", False) is False:
+        version_string = os.popen("xrandr -v").read()
+        version = re.search("xrandr program version\s+([0-9\.]+)", version_string).group(1)
+        xrandr_version.version = Version(version)
+    return xrandr_version.version
+
 def debug_regexp(pattern, string):
     "Use the partial matching functionality of the regex module to display debug info on a non-matching regular expression"
     try:
@@ -296,6 +322,10 @@ def load_profiles(profile_path):
             else:
                 buffer.append(line)
 
+        for output_name in list(config.keys()):
+            if "off" in config[output_name].options:
+                del config[output_name]
+
         profiles[profile] = config
 
     return profiles
@@ -357,8 +387,9 @@ def apply_configuration(configuration, dry_run=False):
     for output in outputs:
         if not configuration[output].edid:
             argv += configuration[output].option_vector
-    if subprocess.call(argv) != 0:
-        return False
+    if argv != base_argv:
+        if subprocess.call(argv) != 0:
+            return False
 
     # Enable remaining outputs in pairs of two
     remaining_outputs = [ x for x in outputs if configuration[x].edid ]
@@ -366,6 +397,12 @@ def apply_configuration(configuration, dry_run=False):
         if subprocess.call((base_argv[:] + configuration[remaining_outputs[index]].option_vector + (configuration[remaining_outputs[index + 1]].option_vector if index < len(remaining_outputs) - 1 else []))) != 0:
             return False
 
+def add_unused_outputs(source_configuration, target_configuration):
+    "Add outputs that are missing in target to target, in 'off' state"
+    for output_name, output in source_configuration.items():
+        if output_name not in target_configuration:
+            target_configuration[output_name] = XrandrOutput(output_name, output.edid, { "off": None })
+
 def generate_virtual_profile(configuration, modes, profile_name):
     "Generate one of the virtual profiles"
     configuration = copy.deepcopy(configuration)
@@ -416,7 +453,11 @@ def exec_scripts(profile_path, script_name):
             subprocess.call(script)
 
 def main(argv):
-    options = dict(getopt.getopt(argv[1:], "s:l:d:cfh", [ "dry-run", "change", "default=", "save=", "load=", "force", "fingerprint", "config", "help" ])[0])
+    try:
+       options = dict(getopt.getopt(argv[1:], "s:l:d:cfh", [ "dry-run", "change", "default=", "save=", "load=", "force", "fingerprint", "config", "help" ])[0])
+    except getopt.GetoptError as e:
+        print(str(e))
+        options = { "--help": True }
 
     profile_path = os.path.expanduser("~/.autorandr")
 
@@ -485,7 +526,12 @@ def main(argv):
         if load_profile in ( x[0] for x in virtual_profiles ):
             profile = generate_virtual_profile(config, modes, load_profile)
         else:
-            profile = profiles[load_profile]
+            try:
+                profile = profiles[load_profile]
+            except KeyError:
+                print("Failed to load profile '%s':\nProfile not found" % load_profile, file=sys.stderr)
+                sys.exit(1)
+        add_unused_outputs(config, profile)
         if profile == config and not "-f" in options and not "--force" in options:
             print("Config already loaded")
             sys.exit(0)
@@ -495,7 +541,7 @@ def main(argv):
                 apply_configuration(profile, True)
             else:
                 exec_scripts(os.path.join(profile_path, load_profile), "preswitch")
-                apply_configuration(profile, True)
+                apply_configuration(profile, False)
                 exec_scripts(os.path.join(profile_path, load_profile), "postswitch")
         except Exception as e:
             print("Failed to apply profile '%s':\n%s" % (load_profile, str(e)), file=sys.stderr)