import sys
from distutils.version import LooseVersion as Version
+from functools import reduce
from itertools import chain
from collections import OrderedDict
+import posix
+
+
virtual_profiles = [
# (name, description, callback)
("common", "Clone all connected outputs at the largest common resolution", None),
-s, --save <profile> save your current setup to profile <profile>
-l, --load <profile> load profile <profile>
-d, --default <profile> make profile <profile> the default profile
+--skip-options <option> comma separated list of xrandr arguments (e.g. "gamma")
+ to skip both in detecting changes and applying a profile
--force force (re)loading of a profile
--fingerprint fingerprint your current hardware setup
--config dump your current xrandr setup
if self.line:
retval.append(" (line %d)" % self.line)
if self.original_exception:
- retval.append(":\n " % self.line)
+ retval.append(":\n ")
retval.append(str(self.original_exception).replace("\n", "\n "))
if self.report_bug:
retval.append("\nThis appears to be a bug. Please help improving autorandr by reporting it upstream."
(?:[\ \t]*tracking\ (?P<tracking>[0-9]+x[0-9]+\+[0-9]+\+[0-9]+))? # Tracking information
(?:[\ \t]*border\ (?P<border>(?:[0-9]+/){3}[0-9]+))? # Border information
(?:\s*(?: # Properties of the output
- Gamma: (?P<gamma>[0-9\.: ]+) | # Gamma value
+ Gamma: (?P<gamma>(?:inf|[0-9\.: e])+) | # Gamma value
Transform: (?P<transform>(?:[\-0-9\. ]+\s+){3}) | # Transformation matrix
EDID: (?P<edid>\s*?(?:\\n\\t\\t[0-9a-f]+)+) | # EDID of the output
(?![0-9])[^:\s][^:\n]+:.*(?:\s\\t[\\t ].+)* # Other properties
))+
\s*
(?P<modes>(?:
- (?P<mode_width>[0-9]+)x(?P<mode_height>[0-9]+).+?\*current.*\s+
- h:.+\s+v:.+clock\s+(?P<rate>[0-9\.]+)Hz\s* | # Interesting (current) resolution: Extract rate
- [0-9]+x[0-9]+(?:(?!\*current).)+\s+h:.+\s+v:.+\s* # Other resolutions
+ (?P<mode_name>\S+).+?\*current.*\s+ # Interesting (current) resolution: Extract rate
+ h:\s+width\s+(?P<mode_width>[0-9]+).+\s+
+ v:\s+height\s+(?P<mode_height>[0-9]+).+clock\s+(?P<rate>[0-9\.]+)Hz\s* |
+ \S+(?:(?!\*current).)+\s+h:.+\s+v:.+\s* # Other resolutions
)*)
"""
XRANDR_OUTPUT_MODES_REGEXP = """(?x)
- (?P<width>[0-9]+)x(?P<height>[0-9]+)
- .*?(?P<preferred>\+preferred)?
- \s+h:.+
- \s+v:.+clock\s+(?P<rate>[0-9\.]+)Hz
+ (?P<name>\S+).+?(?P<preferred>\+preferred)?\s+
+ h:\s+width\s+(?P<width>[0-9]+).+\s+
+ v:\s+height\s+(?P<height>[0-9]+).+clock\s+(?P<rate>[0-9\.]+)Hz\s* |
"""
XRANDR_13_DEFAULTS = {
if xrandr_version() >= Version("1.2"):
options.update(self.XRANDR_12_DEFAULTS)
options.update(self.options)
- return options
+ return { a: b for a, b in options.items() if a not in self.ignored_options }
+
+ @property
+ def filtered_options(self):
+ "Return a dictionary of options without ignored options"
+ return { a: b for a, b in self.options.items() if a not in self.ignored_options }
@property
def option_vector(self):
@property
def option_string(self):
"Return the command line parameters in the configuration file format"
- return "\n".join([ " ".join(option) if option[1] else option[0] for option in chain((("output", self.output),), sorted(self.options.items()))])
+ return "\n".join([ " ".join(option) if option[1] else option[0] for option in chain((("output", self.output),), sorted(self.filtered_options.items()))])
@property
def sort_key(self):
self.output = output
self.edid = edid
self.options = options
+ self.ignored_options = []
self.remove_default_option_values()
+ def set_ignored_options(self, options):
+ "Set a list of xrandr options that are never used (neither when comparing configurations nor when applying them)"
+ self.ignored_options = list(options)
+
def remove_default_option_values(self):
"Remove values from the options dictionary that are superflous"
if "off" in self.options and len(self.options.keys()) > 1:
modes = []
if match["modes"]:
- modes = [ x.groupdict() for x in re.finditer(XrandrOutput.XRANDR_OUTPUT_MODES_REGEXP, match["modes"]) ]
+ modes = [ x.groupdict() for x in re.finditer(XrandrOutput.XRANDR_OUTPUT_MODES_REGEXP, match["modes"]) if x.group("name") ]
if not modes:
raise AutorandrException("Parsing XRandR output failed, couldn't find any display modes", report_bug=True)
if not match["width"]:
options["off"] = None
else:
- if match["mode_width"]:
+ if match["mode_name"]:
+ options["mode"] = match["mode_name"]
+ elif match["mode_width"]:
options["mode"] = "%sx%s" % (match["mode_width"], match["mode_height"])
else:
if match["rotate"] not in ("left", "right"):
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
- if not match["mode_width"]:
+ if not match["mode_name"]:
# 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! Using `%s'." % (match["output"], options["mode"]), file=sys.stderr)
if match["gamma"]:
gamma = match["gamma"].strip()
+ # xrandr prints different values in --verbose than it accepts as a parameter value for --gamma
+ # Also, it is not able to work with non-standard gamma ramps. Finally, it auto-corrects 0 to 1,
+ # so we approximate by 1e-10.
+ gamma = ":".join([ str(max(1e-10, round(1./float(x), 3))) for x in gamma.split(":") ])
options["gamma"] = gamma
if match["rate"]:
options["rate"] = match["rate"]
return self.edid == other.edid
def __eq__(self, other):
- return self.edid_equals(other) and self.output == other.output and self.options == other.options
+ return self.edid_equals(other) and self.output == other.output and self.filtered_options == other.filtered_options
def xrandr_version():
"Return the version of XRandR that this system uses"
for output in configuration:
configuration[output].options = {}
if output in modes:
- configuration[output].options["mode"] = "%sx%s" % common_resolution[-1]
+ configuration[output].options["mode"] = [ x["name"] for x in sorted(modes[output], key=lambda x: 0 if x["preferred"] else 1) if x["width"] == common_resolution[-1][0] and x["height"] == common_resolution[-1][1] ][0]
configuration[output].options["pos"] = "0x0"
else:
configuration[output].options["off"] = None
configuration[output].options = {}
if output in modes:
mode = sorted(modes[output], key=lambda a: int(a["width"])*int(a["height"]) + (10**6 if a["preferred"] else 0))[-1]
- configuration[output].options["mode"] = "%sx%s" % (mode["width"], mode["height"])
+ configuration[output].options["mode"] = mode["name"]
configuration[output].options["rate"] = mode["rate"]
configuration[output].options["pos"] = pos_specifier % shift
shift += int(mode[shift_index])
def main(argv):
try:
- options = dict(getopt.getopt(argv[1:], "s:l:d:cfh", [ "dry-run", "change", "default=", "save=", "load=", "force", "fingerprint", "config", "help" ])[0])
+ options = dict(getopt.getopt(argv[1:], "s:l:d:cfh", [ "dry-run", "change", "default=", "save=", "load=", "force", "fingerprint", "config", "skip-options=", "help" ])[0])
except getopt.GetoptError as e:
- print(str(e))
- options = { "--help": True }
+ print("Failed to parse options: {0}.\n"
+ "Use --help to get usage information.".format(str(e)),
+ file=sys.stderr)
+ sys.exit(posix.EX_USAGE)
profiles = {}
try:
output_configuration(config, sys.stdout)
sys.exit(0)
+ if "--skip-options" in options:
+ skip_options = [ y[2:] if y[:2] == "--" else y for y in ( x.strip() for x in options["--skip-options"].split(",") ) ]
+ for profile in profiles.values():
+ for output in profile["config"].values():
+ output.set_ignored_options(skip_options)
+ for output in config.values():
+ output.set_ignored_options(skip_options)
+
if "-s" in options:
options["--save"] = options["-s"]
if "--save" in options:
try:
main(sys.argv)
except AutorandrException as e:
- print(file=sys.stderr)
print(e, file=sys.stderr)
sys.exit(1)
except Exception as e:
- trace = sys.exc_info()[2]
- while trace.tb_next:
- trace = trace.tb_next
- print("\nUnhandled exception in line %d. Please report this as a bug:\n %s" % (trace.tb_lineno, "\n ".join(str(e).split("\n")),), file=sys.stderr)
- sys.exit(1)
+ if not len(str(e)): # BdbQuit
+ print("Exception: {0}".format(e.__class__.__name__))
+ sys.exit(2)
+
+ print("Unhandled exception ({0}). Please report this as a bug.".format(e), file=sys.stderr)
+ raise