X-Git-Url: https://git.donarmstrong.com/?a=blobdiff_plain;f=autorandr.py;h=c33246f4ddb9c7b0a2052dc645299a36fe9976a7;hb=89bf1ac166e2c124c2b0bd687138b8fddbe74c47;hp=aadb7d4f608e3e179fefe87d7b8f563cc8042d58;hpb=e5ae9d8c97fe6251c2b587de0cb4fbd605196075;p=deb_pkgs%2Fautorandr.git diff --git a/autorandr.py b/autorandr.py index aadb7d4..c33246f 100755 --- a/autorandr.py +++ b/autorandr.py @@ -83,16 +83,21 @@ class XrandrOutput(object): (?: # Differentiate disconnected and connected in first line disconnected | unknown\ connection | - (?Pconnected)\s+ # If connected: - (?: - (?Pprimary\ )? # Might be primary screen + (?Pconnected) + ) + \s* + (?Pprimary\ )? # Might be primary screen + (?:\s* (?P[0-9]+)x(?P[0-9]+) # Resolution (might be overridden below!) - \+(?P[0-9]+)\+(?P[0-9]+)\s+ # Position + \+(?P-?[0-9]+)\+(?P-?[0-9]+)\s+ # Position (?:\(0x[0-9a-fA-F]+\)\s+)? # XID (?P(?:normal|left|right|inverted))\s+ # Rotation (?:(?PX\ and\ Y|X|Y)\ axis)? # Reflection - )? # .. but everything of the above only if the screen is in use. - ).* + )? # .. but everything of the above only if the screen is in use. + (?:[\ \t]*\([^\)]+\))(?:\s*[0-9]+mm\sx\s[0-9]+mm)? + (?:[\ \t]*panning\ (?P[0-9]+x[0-9]+\+[0-9]+\+[0-9]+))? # Panning information + (?:[\ \t]*tracking\ (?P[0-9]+x[0-9]+\+[0-9]+\+[0-9]+))? # Tracking information + (?:[\ \t]*border\ (?P(?:[0-9]+/){3}[0-9]+))? # Border information (?:\s*(?: # Properties of the output Gamma: (?P[0-9\.: ]+) | # Gamma value Transform: (?P(?:[\-0-9\. ]+\s+){3}) | # Transformation matrix @@ -101,9 +106,9 @@ class XrandrOutput(object): ))+ \s* (?P(?: - (?P[0-9]+)x(?P[0-9]+).+?\*current.+\s+ + (?P[0-9]+)x(?P[0-9]+).+?\*current.*\s+ h:.+\s+v:.+clock\s+(?P[0-9\.]+)Hz\s* | # Interesting (current) resolution: Extract rate - [0-9]+x[0-9]+.+\s+h:.+\s+v:.+\s* # Other resolutions + [0-9]+x[0-9]+(?:(?!\*current).)+\s+h:.+\s+v:.+\s* # Other resolutions )*) """ @@ -116,6 +121,7 @@ class XrandrOutput(object): XRANDR_13_DEFAULTS = { "transform": "1,0,0,0,1,0,0,0,1", + "panning": "0x0", } XRANDR_12_DEFAULTS = { @@ -126,6 +132,8 @@ class XrandrOutput(object): XRANDR_DEFAULTS = dict(list(XRANDR_13_DEFAULTS.items()) + list(XRANDR_12_DEFAULTS.items())) + EDID_UNAVAILABLE = "--CONNECTED-BUT-EDID-UNAVAILABLE-" + 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)) @@ -156,6 +164,8 @@ class XrandrOutput(object): def sort_key(self): "Return a key to sort the outputs for xrandr invocation" if not self.edid: + return -2 + if "off" in self.options: return -1 if "pos" in self.options: x, y = map(float, self.options["pos"].split("x")) @@ -196,7 +206,7 @@ class XrandrOutput(object): remainder = xrandr_output[len(match_object.group(0)):] if remainder: raise RuntimeError(("Parsing XRandR output failed, %d bytes left unmatched after regular expression, " - "starting at byte %d with ..'%s'.") % (len(remainder), len(len(match_object.group(0))), remainder[:10])) + "starting at byte %d with ..'%s'.") % (len(remainder), len(match_object.group(0)), remainder[:10])) match = match_object.groupdict() @@ -208,11 +218,12 @@ class XrandrOutput(object): options = {} if not match["connected"]: - options["off"] = None edid = None - elif not match["width"]: + else: + edid = "".join(match["edid"].strip().split()) if match["edid"] else "%s-%s" % (XrandrOutput.EDID_UNAVAILABLE, match["output"]) + + if not match["width"]: options["off"] = None - edid = "".join(match["edid"].strip().split()) else: if match["mode_width"]: options["mode"] = "%sx%s" % (match["mode_width"], match["mode_height"]) @@ -231,6 +242,13 @@ class XrandrOutput(object): elif match["reflect"] == "X and Y": options["reflect"] = "xy" options["pos"] = "%sx%s" % (match["x"], match["y"]) + if match["panning"]: + panning = [ match["panning"] ] + if match["tracking"]: + panning += [ "/", match["tracking"] ] + if match["border"]: + panning += [ "/", match["border"] ] + options["panning"] = "".join(panning) if match["transform"]: 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": @@ -238,13 +256,12 @@ class XrandrOutput(object): if not match["mode_width"]: # TODO We'd need to apply the reverse transformation here. Let's see if someone complains, I doubt that this # special case is actually required. - print("Warning: Output %s has a transformation applied. Could not determine correct mode!", file=sys.stderr) + print("Warning: Output %s has a transformation applied. Could not determine correct mode! Using `%s'." % (match["output"], options["mode"]), file=sys.stderr) if match["gamma"]: gamma = match["gamma"].strip() options["gamma"] = gamma if match["rate"]: options["rate"] = match["rate"] - edid = "".join(match["edid"].strip().split()) return XrandrOutput(match["output"], edid, options), modes @@ -278,9 +295,9 @@ class XrandrOutput(object): def edid_equals(self, other): "Compare to another XrandrOutput's edid and on/off-state, taking legacy autorandr behaviour (md5sum'ing) into account" if self.edid and other.edid: - if len(self.edid) == 32 and len(other.edid) != 32: + if len(self.edid) == 32 and len(other.edid) != 32 and not other.edid.startswith(XrandrOutput.EDID_UNAVAILABLE): return hashlib.md5(binascii.unhexlify(other.edid)).hexdigest() == self.edid - if len(self.edid) != 32 and len(other.edid) == 32: + if len(self.edid) != 32 and len(other.edid) == 32 and not self.edid.startswith(XrandrOutput.EDID_UNAVAILABLE): return hashlib.md5(binascii.unhexlify(self.edid)).hexdigest() == other.edid return self.edid == other.edid @@ -351,7 +368,7 @@ def load_profiles(profile_path): if not os.path.isfile(config_name) or not os.path.isfile(setup_name): continue - edids = dict([ x.strip().split() for x in open(setup_name).readlines() ]) + edids = dict([ x.strip().split() for x in open(setup_name).readlines() if x.strip() ]) config = {} buffer = [] @@ -390,7 +407,7 @@ def find_profiles(current_config, profiles): def profile_blocked(profile_path): "Check if a profile is blocked" - script = os.path.join(profile_path, "blocked") + script = os.path.join(profile_path, "block") if not os.access(script, os.X_OK | os.F_OK): return False return subprocess.call(script) == 0 @@ -425,37 +442,71 @@ def update_mtime(filename): except: return False -def apply_configuration(configuration, dry_run=False): +def apply_configuration(new_configuration, current_configuration, dry_run=False): "Apply a configuration" - outputs = sorted(configuration.keys(), key=lambda x: configuration[x].sort_key) + outputs = sorted(new_configuration.keys(), key=lambda x: new_configuration[x].sort_key) if dry_run: base_argv = [ "echo", "xrandr" ] else: base_argv = [ "xrandr" ] - # Disable all unused outputs - argv = base_argv[:] - disable_argv = [] + # There are several xrandr / driver bugs we need to take care of here: + # - We cannot enable more than two screens at the same time + # See https://github.com/phillipberndt/autorandr/pull/6 + # and commits f4cce4d and 8429886. + # - We cannot disable all screens + # See https://github.com/phillipberndt/autorandr/pull/20 + # - We should disable screens before enabling others, because there's + # a limit on the number of enabled screens + # - We must make sure that the screen at 0x0 is activated first, + # or the other (first) screen to be activated would be moved there. + # - If an active screen already has a transformation and remains active, + # the xrandr call fails with an invalid RRSetScreenSize parameter error. + # Update the configuration in 3 passes in that case. (On Haswell graphics, + # at least.) + + auxiliary_changes_pre = [] + disable_outputs = [] + enable_outputs = [] + remain_active_count = 0 for output in outputs: - if not configuration[output].edid or "off" in configuration[output].options: - disable_argv += configuration[output].option_vector - if disable_argv: - if subprocess.call(base_argv + disable_argv) != 0: + if not new_configuration[output].edid or "off" in new_configuration[output].options: + disable_outputs.append(new_configuration[output].option_vector) + else: + if "off" not in current_configuration[output].options: + remain_active_count += 1 + enable_outputs.append(new_configuration[output].option_vector) + if xrandr_version() >= Version("1.3.0") and "transform" in current_configuration[output].options: + auxiliary_changes_pre.append(["--output", output, "--transform", "none"]) + + # Perform pe-change auxiliary changes + if auxiliary_changes_pre: + argv = base_argv + list(chain.from_iterable(auxiliary_changes_pre)) + if subprocess.call(argv) != 0: + raise RuntimeError("Command failed: %s" % " ".join(argv)) + + # Disable unused outputs, but make sure that there always is at least one active screen + disable_keep = 0 if remain_active_count else 1 + if len(disable_outputs) > disable_keep: + if subprocess.call(base_argv + list(chain.from_iterable(disable_outputs[:-1] if disable_keep else disable_outputs))) != 0: # Disabling the outputs failed. Retry with the next command: # Sometimes disabling of outputs fails due to an invalid RRSetScreenSize. # This does not occur if simultaneously the primary screen is reset. pass else: - disable_argv = [] - - # Enable remaining outputs in pairs of two - remaining_outputs = [ x for x in outputs if configuration[x].edid ] - for index in range(0, len(remaining_outputs), 2): - argv = base_argv[:] - if disable_argv: - argv += disable_argv - disable_argv = [] - argv += configuration[remaining_outputs[index]].option_vector + (configuration[remaining_outputs[index + 1]].option_vector if index < len(remaining_outputs) - 1 else []) + disable_outputs = disable_outputs[-1:] if disable_keep else [] + + # If disable_outputs still has more than one output in it, one of the xrandr-calls below would + # disable the last two screens. This is a problem, so if this would happen, instead disable only + # one screen in the first call below. + if len(disable_outputs) > 0 and len(disable_outputs) % 2 == 0: + # In the context of a xrandr call that changes the display state, `--query' should do nothing + disable_outputs.insert(0, ['--query']) + + # Enable the remaining outputs in pairs of two operations + operations = disable_outputs + enable_outputs + for index in range(0, len(operations), 2): + argv = base_argv + list(chain.from_iterable(operations[index:index+2])) if subprocess.call(argv) != 0: raise RuntimeError("Command failed: %s" % " ".join(argv)) @@ -465,6 +516,12 @@ def add_unused_outputs(source_configuration, target_configuration): if output_name not in target_configuration: target_configuration[output_name] = XrandrOutput(output_name, output.edid, { "off": None }) +def remove_irrelevant_outputs(source_configuration, target_configuration): + "Remove outputs from target that ought to be 'off' and already are" + for output_name, output in source_configuration.items(): + if "off" in output.options and output_name in target_configuration and "off" in target_configuration[output_name].options: + del target_configuration[output_name] + def generate_virtual_profile(configuration, modes, profile_name): "Generate one of the virtual profiles" configuration = copy.deepcopy(configuration) @@ -615,13 +672,14 @@ def main(argv): if load_config == dict(config) and not "-f" in options and not "--force" in options: print("Config already loaded", file=sys.stderr) sys.exit(0) + remove_irrelevant_outputs(config, load_config) try: if "--dry-run" in options: - apply_configuration(load_config, True) + apply_configuration(load_config, config, True) else: exec_scripts(scripts_path, "preswitch") - apply_configuration(load_config, False) + apply_configuration(load_config, config, False) exec_scripts(scripts_path, "postswitch") except Exception as e: print("Failed to apply profile '%s':\n%s" % (load_profile, str(e)), file=sys.stderr)