+ 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
+
+ option_vector = new_configuration[output].option_vector
+ if xrandr_version() >= Version("1.3.0"):
+ for option, off_value in (("transform", "none"), ("panning", "0x0")):
+ if option in current_configuration[output].options:
+ auxiliary_changes_pre.append(["--output", output, "--%s" % option, off_value])
+ else:
+ try:
+ option_index = option_vector.index("--%s" % option)
+ if option_vector[option_index + 1] == XrandrOutput.XRANDR_DEFAULTS[option]:
+ option_vector = option_vector[:option_index] + option_vector[option_index + 2:]
+ except ValueError:
+ pass
+
+ enable_outputs.append(option_vector)
+
+ # Perform pe-change auxiliary changes
+ if auxiliary_changes_pre:
+ argv = base_argv + list(chain.from_iterable(auxiliary_changes_pre))
+ if call_and_retry(argv, dry_run=dry_run) != 0:
+ raise AutorandrException("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:
+ argv = base_argv + list(chain.from_iterable(disable_outputs[:-1] if disable_keep else disable_outputs))
+ if call_and_retry(argv, dry_run=dry_run) != 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_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 call_and_retry(argv, dry_run=dry_run) != 0:
+ raise AutorandrException("Command failed: %s" % " ".join(argv))
+
+
+def is_equal_configuration(source_configuration, target_configuration):
+ """
+ Check if all outputs from target are already configured correctly in source and
+ that no other outputs are active.
+ """
+ for output in target_configuration.keys():
+ if "off" in target_configuration[output].options:
+ if (output in source_configuration or "off" not in source_configuration[output].options):
+ return False
+ else:
+ if (output not in source_configuration) or (source_configuration[output] != target_configuration[output]):
+ return False
+ for output in source_configuration.keys():
+ if "off" in source_configuration[output].options:
+ if output in target_configuration and "off" not in target_configuration.options:
+ return False
+ else:
+ if output not in target_configuration:
+ return False
+ return True
+
+
+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 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:
+ if output_name in target_configuration:
+ if "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)
+ if profile_name == "common":
+ mode_sets = []
+ for output, output_modes in modes.items():
+ mode_set = set()
+ if configuration[output].edid:
+ for mode in output_modes:
+ mode_set.add((mode["width"], mode["height"]))
+ mode_sets.append(mode_set)
+ common_resolution = reduce(lambda a, b: a & b, mode_sets[1:], mode_sets[0])
+ common_resolution = sorted(common_resolution, key=lambda a: int(a[0]) * int(a[1]))
+ if common_resolution:
+ for output in configuration:
+ configuration[output].options = {}
+ if output in modes and configuration[output].edid:
+ modes_sorted = sorted(modes[output], key=lambda x: 0 if x["preferred"] else 1)
+ modes_filtered = [x for x in modes_sorted if (x["width"], x["height"]) == common_resolution[-1]]
+ mode = modes_filtered[0]
+ configuration[output].options["mode"] = mode['name']
+ configuration[output].options["pos"] = "0x0"
+ else:
+ configuration[output].options["off"] = None
+ elif profile_name in ("horizontal", "vertical"):
+ shift = 0
+ if profile_name == "horizontal":
+ shift_index = "width"
+ pos_specifier = "%sx0"
+ else:
+ shift_index = "height"
+ pos_specifier = "0x%s"
+
+ for output in configuration:
+ configuration[output].options = {}
+ if output in modes and configuration[output].edid:
+ def key(a):
+ score = int(a["width"]) * int(a["height"])
+ if a["preferred"]:
+ score += 10**6
+ return score
+ output_modes = sorted(modes[output], key=key)
+ mode = output_modes[-1]
+ configuration[output].options["mode"] = mode["name"]
+ configuration[output].options["rate"] = mode["rate"]
+ configuration[output].options["pos"] = pos_specifier % shift
+ shift += int(mode[shift_index])
+ else:
+ configuration[output].options["off"] = None
+ elif profile_name == "clone-largest":
+ modes_unsorted = [output_modes[0] for output, output_modes in modes.items()]
+ modes_sorted = sorted(modes_unsorted, key=lambda x: int(x["width"]) * int(x["height"]), reverse=True)
+ biggest_resolution = modes_sorted[0]
+ for output in configuration:
+ configuration[output].options = {}
+ if output in modes and configuration[output].edid:
+ def key(a):
+ score = int(a["width"]) * int(a["height"])
+ if a["preferred"]:
+ score += 10**6
+ return score
+ output_modes = sorted(modes[output], key=key)
+ mode = output_modes[-1]
+ configuration[output].options["mode"] = mode["name"]
+ configuration[output].options["rate"] = mode["rate"]
+ configuration[output].options["pos"] = "0x0"
+ scale = max(float(biggest_resolution["width"]) / float(mode["width"]),
+ float(biggest_resolution["height"]) / float(mode["height"]))
+ mov_x = (float(mode["width"]) * scale - float(biggest_resolution["width"])) / -2
+ mov_y = (float(mode["height"]) * scale - float(biggest_resolution["height"])) / -2
+ configuration[output].options["transform"] = "{},0,{},0,{},{},0,0,1".format(scale, mov_x, scale, mov_y)
+ else:
+ configuration[output].options["off"] = None
+ elif profile_name == "off":
+ for output in configuration:
+ for key in list(configuration[output].options.keys()):
+ del configuration[output].options[key]
+ configuration[output].options["off"] = None
+ return configuration
+
+
+def print_profile_differences(one, another):
+ "Print the differences between two profiles for debugging"
+ if one == another:
+ return
+ print("| Differences between the two profiles:")
+ for output in set(chain.from_iterable((one.keys(), another.keys()))):
+ if output not in one:
+ if "off" not in another[output].options:
+ print("| Output `%s' is missing from the active configuration" % output)
+ elif output not in another:
+ if "off" not in one[output].options:
+ print("| Output `%s' is missing from the new configuration" % output)
+ else:
+ for line in one[output].verbose_diff(another[output]):
+ print("| [Output %s] %s" % (output, line))
+ print("\\-")