Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
openSUSE:Factory:Rebuild
autorandr
autorandr-1.15.0.1709469470.obscpio
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File autorandr-1.15.0.1709469470.obscpio of Package autorandr
07070100000000000081A400000000000000000000000165E46F1E0000002D000000000000000000000000000000000000002400000000autorandr-1.15.0.1709469470/.flake8[flake8] ignore = E722 max-line-length = 130 07070100000001000081A400000000000000000000000165E46F1E00000007000000000000000000000000000000000000002700000000autorandr-1.15.0.1709469470/.gitignore.*.swp 07070100000002000081A400000000000000000000000165E46F1E00001DE8000000000000000000000000000000000000002500000000autorandr-1.15.0.1709469470/MakefileDESTDIR=/ PREFIX=/usr/ RPM_SPEC=contrib/packaging/rpm/autorandr.spec CFLAGS?=-O2 -Wall CLEANUP_FILES= .PHONY: all install uninstall autorandr bash_completion autostart_config pmutils systemd udev all: @echo "Call \"make install\" to install this program." @echo "Call \"make uninstall\" to remove this program." @echo @echo "The following components were autodetected and will be installed:" @echo " "$(DEFAULT_TARGETS) @echo @echo "The following locations have been detected (from pkg-config):" @echo " - BASH_COMPLETIONS_DIR: $(BASH_COMPLETIONS_DIR)" @echo " - SYSTEMD_UNIT_DIR: $(SYSTEMD_UNIT_DIR)" @echo " - UDEV_RULES_DIR: $(UDEV_RULES_DIR)" @echo " - PM_SLEEPHOOKS_DIR: $(PM_SLEEPHOOKS_DIR)" @echo @echo "You can use the TARGETS variable to override this, but need to set" @echo "the SYSTEMD_UNIT_DIR, PM_SLEEPHOOKS_DIR and UDEV_RULES_DIR variables" @echo "in case they were not detected correctly." @echo @echo 'E.g. "make install TARGETS='autorandr pmutils' PM_UTILS_DIR=/etc/pm/sleep.d".' @echo @echo "An additional TARGETS variable \"launcher\" is available. This" @echo "installs a launcher called \"autorandr_launcher\". The launcher" @echo "is able to be run by the user and calls autorandr automatically" @echo "without using udev rules. The launcher is an alternative to the" @echo "udev/systemd setup that is more stable for some users." @echo @echo "The following additional targets are available:" @echo @echo " make deb creates a Debian package" @echo " make rpm creates a RPM package" # Rules for autorandr itself DEFAULT_TARGETS=autorandr install_autorandr: mkdir -p ${DESTDIR}${PREFIX}/bin install -m 755 autorandr.py ${DESTDIR}${PREFIX}/bin/autorandr uninstall_autorandr: rm -f ${DESTDIR}${PREFIX}/bin/autorandr # Rules for bash-completion BASH_COMPLETIONS_DIR:=$(shell pkg-config --variable=completionsdir bash-completion 2>/dev/null) ifneq (,$(BASH_COMPLETIONS_DIR)) DEFAULT_TARGETS+=bash_completion endif install_bash_completion: mkdir -p ${DESTDIR}/${BASH_COMPLETIONS_DIR} install -m 644 contrib/bash_completion/autorandr ${DESTDIR}/${BASH_COMPLETIONS_DIR}/autorandr uninstall_bash_completion: rm -f ${DESTDIR}/${BASH_COMPLETIONS_DIR}/autorandr # Rules for autostart config XDG_AUTOSTART_DIR=/etc/xdg/autostart DEFAULT_TARGETS+=autostart_config install_autostart_config: mkdir -p ${DESTDIR}/${XDG_AUTOSTART_DIR} install -m 644 contrib/etc/xdg/autostart/autorandr.desktop ${DESTDIR}/${XDG_AUTOSTART_DIR}/autorandr.desktop # KDE-specific autostart (workaround for https://github.com/systemd/systemd/issues/18791) install -m 644 contrib/etc/xdg/autostart/autorandr.desktop ${DESTDIR}/${XDG_AUTOSTART_DIR}/autorandr-kde.desktop desktop-file-edit --remove-key=X-GNOME-Autostart-Phase --add-only-show-in=KDE ${DESTDIR}/${XDG_AUTOSTART_DIR}/autorandr-kde.desktop ifneq ($(PREFIX),/usr/) sed -i -re 's#/usr/bin/autorandr#$(subst #,\#,${PREFIX})/bin/autorandr#g' ${DESTDIR}/${XDG_AUTOSTART_DIR}/autorandr.desktop sed -i -re 's#/usr/bin/autorandr#$(subst #,\#,${PREFIX})/bin/autorandr#g' ${DESTDIR}/${XDG_AUTOSTART_DIR}/autorandr-kde.desktop endif uninstall_autostart_config: rm -f ${DESTDIR}/${XDG_AUTOSTART_DIR}/autorandr.desktop rm -f ${DESTDIR}/${XDG_AUTOSTART_DIR}/autorandr-kde.desktop # Rules for systemd SYSTEMD_UNIT_DIR:=$(shell pkg-config --variable=systemdsystemunitdir systemd 2>/dev/null) ifneq (,$(SYSTEMD_UNIT_DIR)) DEFAULT_TARGETS+=systemd endif install_systemd: $(if $(SYSTEMD_UNIT_DIR),,$(error SYSTEMD_UNIT_DIR is not defined)) mkdir -p ${DESTDIR}/${SYSTEMD_UNIT_DIR} install -m 644 contrib/systemd/autorandr.service ${DESTDIR}/${SYSTEMD_UNIT_DIR}/autorandr.service install -m 644 contrib/systemd/autorandr-lid-listener.service ${DESTDIR}/${SYSTEMD_UNIT_DIR}/autorandr-lid-listener.service ifneq ($(PREFIX),/usr/) sed -i -re 's#/usr/bin/autorandr#$(subst #,\#,${PREFIX})/bin/autorandr#g' ${DESTDIR}/${SYSTEMD_UNIT_DIR}/autorandr.service endif @echo @echo "To activate the systemd units, run this command as root:" @echo " systemctl daemon-reload" @echo " systemctl enable autorandr.service" @echo " systemctl enable autorandr-lid-listener.service" @echo uninstall_systemd: $(if $(SYSTEMD_UNIT_DIR),,$(error SYSTEMD_UNIT_DIR is not defined)) rm -f ${DESTDIR}/${SYSTEMD_UNIT_DIR}/autorandr.service rm -f ${DESTDIR}/${SYSTEMD_UNIT_DIR}/autorandr-lid-listener.service # Rules for pmutils PM_SLEEPHOOKS_DIR:=$(shell pkg-config --variable=pm_sleephooks pm-utils 2>/dev/null) ifneq (,$(PM_SLEEPHOOKS_DIR)) ifeq (,$(SYSTEMD_UNIT_DIR)) DEFAULT_TARGETS+=pmutils endif endif install_pmutils: $(if $(PM_SLEEPHOOKS_DIR),,$(error PM_SLEEPHOOKS_DIR is not defined)) mkdir -p ${DESTDIR}/${PM_SLEEPHOOKS_DIR} install -m 755 contrib/pm-utils/40autorandr ${DESTDIR}/${PM_SLEEPHOOKS_DIR}/40autorandr ifneq ($(PREFIX),/usr/) sed -i -re 's#/usr/bin/autorandr#$(subst #,\#,${PREFIX})/bin/autorandr#g' ${DESTDIR}/${PM_SLEEPHOOKS_DIR}/40autorandr endif uninstall_pmutils: $(if $(PM_SLEEPHOOKS_DIR),,$(error PM_SLEEPHOOKS_DIR is not defined)) rm -f ${DESTDIR}/${PM_SLEEPHOOKS_DIR}/40autorandr # Rules for udev UDEV_RULES_DIR:=$(shell pkg-config --variable=udevdir udev 2>/dev/null)/rules.d ifneq (/rules.d,$(UDEV_RULES_DIR)) DEFAULT_TARGETS+=udev endif install_udev: $(if $(UDEV_RULES_DIR),,$(error UDEV_RULES_DIR is not defined)) mkdir -p ${DESTDIR}/${UDEV_RULES_DIR}/ echo 'ACTION=="change", SUBSYSTEM=="drm", RUN+="$(if $(findstring systemd, $(DEFAULT_TARGETS)),/bin/systemctl start --no-block autorandr.service,${PREFIX}/bin/autorandr --batch --change --default default)"' > ${DESTDIR}/${UDEV_RULES_DIR}/40-monitor-hotplug.rules @echo @echo "To activate the udev rules, run this command as root:" @echo " udevadm control --reload-rules" @echo uninstall_udev: $(if $(UDEV_RULES_DIR),,$(error UDEV_RULES_DIR is not defined)) rm -f ${DESTDIR}/${UDEV_RULES_DIR}/40-monitor-hotplug.rules # Rules for manpage MANDIR:=${PREFIX}/share/man/man1 DEFAULT_TARGETS+=manpage install_manpage: mkdir -p ${DESTDIR}/${MANDIR} cp autorandr.1 ${DESTDIR}/${MANDIR} uninstall_manpage: rm -f ${DESTDIR}/${MANDIR}/autorandr.1 # Rules for launcher LAUNCHER_LDLIBS=$(shell pkg-config --libs pkg-config xcb xcb-randr 2>/dev/null) ifneq (,$(LAUNCHER_LDLIBS)) CLEANUP_FILES+=contrib/autorandr_launcher/autorandr-launcher LAUNCHER_CFLAGS=$(shell pkg-config --cflags pkg-config xcb xcb-randr 2>/dev/null) DEF_AUTORANDR_PATH="-DAUTORANDR_PATH=\"${DESTDIR}${PREFIX}/bin/autorandr\"" contrib/autorandr_launcher/autorandr-launcher: contrib/autorandr_launcher/autorandr_launcher.c $(CC) $(CFLAGS) $(LAUNCHER_CFLAGS) $(DEF_AUTORANDR_PATH) -o $@ $+ $(LDFLAGS) $(LAUNCHER_LDLIBS) $(LDLIBS) install_launcher: contrib/autorandr_launcher/autorandr-launcher mkdir -p ${DESTDIR}${PREFIX}/bin install -m 755 contrib/autorandr_launcher/autorandr-launcher ${DESTDIR}${PREFIX}/bin/autorandr-launcher mkdir -p ${DESTDIR}/${XDG_AUTOSTART_DIR} install -m 644 contrib/etc/xdg/autostart/autorandr-launcher.desktop ${DESTDIR}/${XDG_AUTOSTART_DIR}/autorandr-launcher.desktop ifneq ($(PREFIX),/usr/) sed -i -re 's#/usr/bin/autorandr-launcher#$(subst #,\#,${PREFIX})/bin/autorandr-launcher#g' ${DESTDIR}/${XDG_AUTOSTART_DIR}/autorandr-launcher.desktop endif endif uninstall_launcher: rm -f ${DESTDIR}${PREFIX}/bin/autorandr-launcher rm -f ${DESTDIR}/${XDG_AUTOSTART_DIR}/autorandr-launcher.desktop TARGETS=$(DEFAULT_TARGETS) install: $(patsubst %,install_%,$(TARGETS)) uninstall: $(patsubst %,uninstall_%,$(TARGETS)) deb: ./contrib/packaging/debian/make_deb.sh rpm: spectool -g -R $(RPM_SPEC) rpmbuild -ba $(RPM_SPEC) clean: rm -f $(CLEANUP_FILES) 07070100000003000081A400000000000000000000000165E46F1E00003AAE000000000000000000000000000000000000002600000000autorandr-1.15.0.1709469470/README.md# autorandr Automatically select a display configuration based on connected devices ## Branch information This is a compatible Python rewrite of [wertarbyte/autorandr](https://github.com/wertarbyte/autorandr). Contributions for bash-completion, fd.o/XDG autostart, Nitrogen, pm-utils, and systemd can be found under [contrib](contrib/). The original [wertarbyte/autorandr](https://github.com/wertarbyte/autorandr) tree is unmaintained, with lots of open pull requests and issues. I forked it and merged what I thought were the most important changes. If you are searching for that version, see the [`legacy` branch](https://github.com/phillipberndt/autorandr/tree/legacy). Note that the Python version is better suited for non-standard configurations, like if you use `--transform` or `--reflect`. If you use `auto-disper`, you have to use the bash version, as there is no disper support in the Python version (yet). Both versions use a compatible configuration file format, so you can, to some extent, switch between them. I will maintain the `legacy` branch until @wertarbyte finds the time to maintain his branch again. If you are interested in why there are two versions around, see [#7](https://github.com/phillipberndt/autorandr/issues/7), [#8](https://github.com/phillipberndt/autorandr/issues/8) and especially [#12](https://github.com/phillipberndt/autorandr/issues/12) if you are unhappy with this version and would like to contribute to the bash version. ## License information and authors autorandr is available under the terms of the GNU General Public License (version 3). Contributors to this version of autorandr are: * Adrián López * andersonjacob * Alexander Lochmann * Alexander Wirt * Brice Waegeneire * Chris Dunder * Christoph Gysin * Christophe-Marie Duquesne * Daniel Hahler * Maciej Sitarz * Mathias Svensson * Matthew R Johnson * Nazar Mokrynskyi * Phillip Berndt * Rasmus Wriedt Larsen * Sam Coulter * Simon Wydooghe * Stefan Tomanek * stormc * tachylatus * Timo Bingmann * Timo Kaufmann * Tomasz Bogdal * Victor Häggqvist * Jan-Oliver Kaiser * Alexandre Viau ## Installation/removal You can use the `autorandr.py` script as a stand-alone binary. If you'd like to install it as a system-wide application, there is a Makefile included that also places some configuration files in appropriate directories such that autorandr is invoked automatically when a monitor is connected or removed, the system wakes up from suspend, or a user logs into an X11 session. Run `make install` as root to install it. If you prefer to have a system wide install managed by your package manager, you can * Use the [official Arch package](https://archlinux.org/packages/extra/any/autorandr/). * Use the [official Debian package](https://packages.debian.org/sid/x11/autorandr) on sid * Use the [FreeBSD Ports Collection](https://www.freshports.org/x11/autorandr/) on FreeBSD. * Use the [official Gentoo package](https://packages.gentoo.org/packages/x11-misc/autorandr). * Use the [nix package](https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/services/misc/autorandr.nix) on NixOS. * Use the [guix package](https://git.savannah.gnu.org/cgit/guix.git/log/gnu/packages/xdisorg.scm?qt=grep&q=autorandr) on Guix. * Use the [SlackBuild](https://slackbuilds.org/repository/14.2/desktop/autorandr/) on Slackware. * Use the automated nightlies generated by the [openSUSE build service](https://build.opensuse.org/package/show/home:phillipberndt/autorandr) for various distributions (RPM and DEB based). * Use the [X binary package system](https://wiki.voidlinux.eu/XBPS)' on Void Linux * Build a .deb-file from the source tree using `make deb`. * Build a .rpm-file from the source tree using `make rpm`. We appreciate packaging scripts for other distributions, please file a pull request if you write one. If you prefer `pip` over your package manager, you can install autorandr with: sudo pip install "git+http://github.com/phillipberndt/autorandr#egg=autorandr" or simply sudo pip install autorandr if you prefer to use a stable version. ## How to use Save your current display configuration and setup with: autorandr --save mobile Connect an additional display, configure your setup and save it: autorandr --save docked Now autorandr can detect which hardware setup is active: $ autorandr mobile docked (detected) To automatically reload your setup: $ autorandr --change To manually load a profile: $ autorandr --load <profile> or simply: $ autorandr <profile> autorandr tries to avoid reloading an identical configuration. To force the (re)configuration: $ autorandr --load <profile> --force To prevent a profile from being loaded, place a script call _block_ in its directory. The script is evaluated before the screen setup is inspected, and in case of it returning a value of 0 the profile is skipped. This can be used to query the status of a docking station you are about to leave. If no suitable profile can be identified, the current configuration is kept. To change this behaviour and switch to a fallback configuration, specify `--default <profile>`. The system-wide installation of autorandr by default calls autorandr with a parameter `--default default`. There are three special, virtual configurations called `horizontal`, `vertical` and `common`. They automatically generate a configuration that incorporates all screens connected to the computer. You can symlink `default` to one of these names in your configuration directory to have autorandr use any of them as the default configuration without you having to change the system-wide configuration. You can store default values for any option in an INI-file located at `~/.config/autorandr/settings.ini`. In a `config` section, you may place any default values in the form `option-name=option-argument`. A common and effective use of this is to specify default `skip-options`, for instance skipping the `gamma` setting if using [`redshift`](https://github.com/jonls/redshift) as a daemon. To implement the equivalent of `--skip-options gamma`, your `settings.ini` file should look like this: ``` [config] skip-options=gamma ``` ## Advanced usage ### Hook scripts Three more scripts can be placed in the configuration directory (as defined by the [XDG spec](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html), usually `~/.config/autorandr` or `~/.autorandr` if you have an old installation for user configuration and `/etc/xdg/autorandr` for system wide configuration): - `postswitch` is executed *after* a mode switch has taken place. This can be used to notify window managers or other applications about the switch. - `preswitch` is executed *before* a mode switch takes place. - `postsave` is executed after a profile was stored or altered. - `predetect` is executed before autorandr attempts to run xrandr. These scripts must be executable and can be placed directly in the configuration directory, where they will always be executed, or in the profile subdirectories, where they will only be executed on changes regarding that specific profile. Instead (or in addition) to these scripts, you can also place as many executable files as you like in subdirectories called `script_name.d` (e.g. `postswitch.d`). The order of execution of scripts in these directories is by file name, you can force a certain ordering by naming them `10-wallpaper`, `20-restart-wm`, etc. If a script with the same name occurs multiple times, user configuration takes precedence over system configuration (as specified by the [XDG spec](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html)) and profile configuration over general configuration. As a concrete example, suppose you have the files - `/etc/xdg/autorandr/postswitch` - `~/.config/autorandr/postswitch` - `~/.config/autorandr/postswitch.d/notify-herbstluftwm` - `~/.config/autorandr/docked/postswitch` and switch from `mobile` to `docked`. Then `~/.config/autorandr/docked/postswitch` is executed, since the profile specific configuration takes precedence, and `~/.config/autorandr/postswitch.d/notify-herbstluftwm` is executed, since it has a unique name. If you switch back from `docked` to `mobile`, `~/.config/autorandr/postswitch` is executed instead of the `docked` specific `postswitch`. If you experience issues with xrandr being executed too early after connecting a new monitor, then you can use a `predetect` script to delay the execution. Write e.g. `sleep 1` into that file to make autorandr wait a second before running `xrandr`. #### Variables Some of autorandr's state is exposed as environment variables prefixed with `AUTORANDR_`, such as: - `AUTORANDR_CURRENT_PROFILE` - `AUTORANDR_CURRENT_PROFILES` - `AUTORANDR_PROFILE_FOLDER` - `AUTORANDR_MONITORS` with the intention that they can be used within the hook scripts. For instance, you might display which profile has just been activated by including the following in a `postswitch` script: ```sh notify-send -i display "Display profile" "$AUTORANDR_CURRENT_PROFILE" ``` The one kink is that during `preswitch`, `AUTORANDR_CURRENT_PROFILE` is reporting the *upcoming* profile rather than the *current* one. ### Wildcard EDID matching The EDID strings in the `~/.config/autorandr/*/setup` files may contain an asterisk to enable wildcard matching: Such EDIDs are matched against connected monitors using the usual file name globbing rules. This can be used to create profiles matching multiple (or any) monitors. ### udev triggers with NVidia cards In order for `udev` to detect `drm` events from the native NVidia driver, the kernel parameter `nvidia-drm.modeset` must be set to 1. For example, add a file `/etc/modprobe.d/nvidia-drm-modeset.conf`: ``` options nvidia_drm modeset=1 ``` ### Wayland Before running autorandr will check the environment for the `WAYLAND_DISPLAY` variable to check if the program is running in a Wayland session. This is to avoid issues between usage of xrandr in Wayland environments. If you need to run autorandr in a Wayland environment, one workaround is to unset the `WAYLAND_DISPLAY` variable before running the program, such as: ``` WAYLAND_DISPLAY= autorandr ``` ## Changelog **autorandr 1.15** * *2023-11-27* Several regex literal bug fixes * *2023-12-27* Fix #375: Listen to correct events in launcher * *2024-03-03* Fix #367: Skip profiles without outputs **autorandr 1.14** * *2023-06-22* Direct --match-edid renaming of output messages to stderr * *2023-06-22* Add Wayland awareness * *2023-06-22* Various minor auxiliary tooling bug fixes, see git-log **autorandr 1.13.3** * *2023-01-24* Revert udev rule to rely on "change" event (see #324) **autorandr 1.13.2** * *2023-01-23* Fix autostart in KDE (see #320) * *2023-01-23* Match add/remove rather than change in udev rule (see #321) * *2023-01-23* Fix wildcard use in EDIDs (see #322) * *2023-01-23* Do a final xrandr call to set the frame buffer size (see #319) **autorandr 1.13.1** * *2023-01-16* Fix bug with Version comparison **autorandr 1.13** * *2023-01-15* Add reversed horizontal/vertical profiles * *2023-01-15* Fix distutils deprecation warning * *2023-01-15* Print error when user script fails * *2022-12-01* Support `--skip-options set` to skip setting properties **autorandr 1.12.1** * *2021-12-22* Fix `--match-edid` (see #273) **autorandr 1.12** * *2021-12-16* Switch default interpreter to Python 3 * *2021-12-16* Add `--list` to list all profiles * *2021-12-16* Add `--cycle` to cycle all detected profiles * *2021-12-16* Store display properties (see #204) **autorandr 1.11** * *2020-05-23* Handle empty sys.executable * *2020-06-08* Fix Python 2 compatibility * *2020-10-06* Set group membership of users in batch mode **autorandr 1.10.1** * *2020-05-04* Revert making the launcher the default (fixes #195) **autorandr 1.10** * *2020-04-23* Fix hook script execution order to match description from readme * *2020-04-11* Handle negative gamma values (fixes #188) * *2020-04-11* Sort approximate matches in detected profiles by quality of match * *2020-01-31* Handle non-ASCII environment variables (fixes #180) * *2019-12-31* Fix output positioning if the top-left output is not the first * *2019-12-31* Accept negative gamma values (and interpret them as 0) * *2019-12-31* Prefer the X11 launcher over systemd/udev configuration **autorandr 1.9** * *2019-11-10* Count closed lids as disconnected outputs * *2019-10-05* Do not overwrite existing configurations without `--force` * *2019-08-16* Accept modes that don't match the WWWxHHH pattern * *2019-03-22* Improve bash autocompletion * *2019-03-21* Store CRTC values in configurations * *2019-03-24* Fix handling of recently disconnected outputs (See #128 and #143) **autorandr 1.8.1** * *2019-03-18* Removed mandb call from Makefile **autorandr 1.8** * *2019-02-17* Add an X11 daemon that runs autorandr when a display connects (by @rliou92, #127) * *2019-02-17* Replace width=0 check with disconnected to detect disconnected monitors (by @joseph-jones, #139) * *2019-02-17* Fix handling of empty padding (by @jschwab, #138) * *2019-02-17* Add a man page (by @somers-all-the-time, #133) **autorandr 1.7** * *2018-09-25* Fix FB size computation with rotated screens (by @Janno, #117) **autorandr 1.6** * *2018-04-19* Bugfix: Do not load default profile unless --change is set * *2018-04-30* Added a `AUTORANDR_MONITORS` variable to hooks (by @bricewge, #106) * *2018-06-29* Fix detection of current configuration if extra monitors are active * *2018-07-11* Bugfix in the latest change: Correctly handle "off" minitors when comparing * *2018-07-19* Do not kill spawned user processes from systemd unit * *2018-07-20* Correctly handle "off" monitors when comparing -- fixup for another bug. **autorandr 1.5** * *2018-01-03* Add --version * *2018-01-04* Fixed vertical/horizontal/clone-largest virtual profiles * *2018-03-07* Output all non-error messages to stdout instead of stderr * *2018-03-25* Add --detected and --current to filter the profile list output * *2018-03-25* Allow wildcard matching in EDIDs **autorandr 1.4** * *2017-12-22* Fixed broken virtual profile support * *2017-12-14* Added support for a settings file * *2017-12-14* Added a virtual profile `off`, which disables all screens **autorandr 1.3** * *2017-11-13* Add a short form for `--load` * *2017-11-21* Fix environment stealing in `--batch` mode (See #87) **autorandr 1.2** * *2017-07-16* Skip `--panning` unless it is required (See #72) * *2017-10-13* Add `clone-largest` virtual profile **autorandr 1.1** * *2017-06-07* Call systemctl with `--no-block` from udev rule (See #61) * *2017-01-20* New script hook, `predetect` * *2017-01-18* Accept comments (lines starting with `#`) in config/setup files **autorandr 1.0** * *2016-12-07* Tag the current code as version 1.0.0; see github issue #54 * *2016-10-03* Install a desktop file to `/etc/xdg/autostart` by default 07070100000004000081A400000000000000000000000165E46F1E000012C5000000000000000000000000000000000000002800000000autorandr-1.15.0.1709469470/autorandr.1.TH AUTORANDR 1 .SH NAME autorandr \- automatically select a display configuration based on connected devices .SH SYNOPSIS .B autorandr [\fIOPTION\fR] [\fIPROFILE\fR] .SH DESCRIPTION .PP This program automatically detects connected display hardware and then loads an appropriate X11 setup using xrandr. It also supports the use of display profiles for different hardware setups. .PP Autorandr also includes several virtual configurations including \fBoff\fR, \fBcommon\fR, \fBclone-largest\fR, \fBhorizontal\fR, and \fBvertical\fR. See the documentation for explanation of each. .SH OPTIONS .TP \fB\-h\fR, \fB\-\-help \fRDisplay help text and exit .TP \fB\-c\fR, \fB\-\-change \fRAutomatically load the first detected profile .TP \fB\-d\fR, \fB\-\-default \fIPROFILE \fRMake profile \fIPROFILE\fR the default profile. The default profile is used if no suitable profile can be identified. Else, the current configuration is kept. .TP \fB\-l\fR, \fB\-\-load \fIPROFILE \fRLoad profile \fIPROFILE .TP \fB\-s\fR, \fB\-\-save \fIPROFILE \fRSave the current setup to profile \fIPROFILE .TP \fB\-r\fR, \fB\-\-remove \fIPROFILE \fRRemove profile \fIPROFILE .TP .BR \-\-batch \fRRun autorandr for all users with active X11 sessions .TP .BR \-\-current List only the current (active) configuration(s) .TP .BR \-\-config Dump the variable values of your current xrandr setup .TP .BR \-\-cycle Cycle through all detected profiles .TP .BR \-\-debug Enable verbose output .TP .BR \-\-detected List only the detected (i.e. available) configuration(s) .TP .BR \-\-dry\-run Don't change anything, only print the xrandr commands .TP .BR \-\-fingerprint Fingerprint the current hardware setup .TP .BR \-\-match-edid Match displays based on edid instead of name .TP .BR \-\-ignore-lid By default, closed lids are considered as disconnected if other outputs are detected. This flag disables this behaviour. .TP .BR \-\-force Force loading or reloading of a profile .TP .BR \-\-list List all profiles .TP \fB\-\-skip\-options [\fIOPTION\fR] ... \fRSet a comma\-separated list of xrandr arguments to skip both in change detection and profile application. See \fBxrandr(1)\fR for xrandr arguments. .TP .BR \-\-version Show version information and exit .SH FILES Configuration files are searched for in the \fIautorandr \fRdirectory in the colon separated list of paths in \fI$XDG_CONFIG_DIRS \fR- or in \fI/etc/xdg \fRif that var is not set. They are then looked for in \fI~/.autorandr \fRand if that doesn't exist, in \fI$XDG_CONFIG_HOME/autorandr \fRor in \fI~/.config/autorandr\fR if that var is unset. In each of those directories it looks for directories with \fIconfig\fR and \fIsetup\fR in them. It is best to manage these files with the \fBautorandr\fR utility. .SH DEFAULT OPTIONS You can store default values for any option in an INI-file located at \fI~/.config/autorandr/settings.ini\fR. In a config section, you may place any default values in the form \fIoption-name=option-argument\fR. .SH HOOK SCRIPTS Four more scripts can be placed in the configuration directory: .TP \fIpostswitch\fR Executed after a mode switch has taken place. This can be used to notify window managers or other applications about the switch. .TP \fIpreswitch\fR Executed before a mode switch takes place. .TP \fIpostsave\fR Executed after a profile was stored or altered. .TP \fIpredetect\fR Executed before autorandr attempts to run xrandr. .PP These scripts must be executable and can be placed directly in the configuration directory, where they will always be executed, or in the profile subdirectories, where they will only be executed on changes regarding that specific profile. Instead (or in addition) to these scripts, you can also place as many executable files as you like in subdirectories called script_name.d (e.g. postswitch.d). .PP Some of autorandr's state is exposed as environment variables prefixed with \fIAUTORANDR_\fR, such as: \fIAUTORANDR_CURRENT_PROFILE\fR, \fIAUTORANDR_CURRENT_PROFILES\fR, \fIAUTORANDR_PROFILE_FOLDER\fR, and \fIAUTORANDR_MONITORS\fR with the intention that they can be used within the hook scripts. The one kink is that during \fIpreswitch\fR, \fIAUTORANDR_CURRENT_PROFILE\fR is reporting the upcoming profile rather than the current one. .SH AUTHOR \fRPhillip Berndt <phillip.berndt@googlemail.com> .br See https://github.com/phillipberndt/autorandr for a full list of contributors. .SH REPORTING BUGS \fRReport issues upstream on GitHub: https://github.com/phillipberndt/autorandr/issues .br \fRPlease attach the output of \fBxrandr --verbose\fR to your bug report if appropriate. .SH SEE ALSO \fRFor examples, advanced usage (including predefined per-profile & global hooks and wildcard EDID matching), and full documentation, see https://github.com/phillipberndt/autorandr. 07070100000005000081ED00000000000000000000000165E46F1E00012672000000000000000000000000000000000000002900000000autorandr-1.15.0.1709469470/autorandr.py#!/usr/bin/env python3 # encoding: utf-8 # # autorandr.py # Copyright (c) 2015, Phillip Berndt # # Autorandr rewrite in Python # # This script aims to be fully compatible with the original autorandr. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from __future__ import print_function import binascii import copy import getopt import hashlib import math import os import posix import pwd import re import shlex import subprocess import sys import shutil import time import glob from collections import OrderedDict from functools import reduce from itertools import chain if sys.version_info.major == 2: import ConfigParser as configparser else: import configparser __version__ = "1.15" try: input = raw_input except NameError: pass virtual_profiles = [ # (name, description, callback) ("off", "Disable all outputs", None), ("common", "Clone all connected outputs at the largest common resolution", None), ("clone-largest", "Clone all connected outputs with the largest resolution (scaled down if necessary)", None), ("horizontal", "Stack all connected outputs horizontally at their largest resolution", None), ("vertical", "Stack all connected outputs vertically at their largest resolution", None), ("horizontal-reverse", "Stack all connected outputs horizontally at their largest resolution in reverse order", None), ("vertical-reverse", "Stack all connected outputs vertically at their largest resolution in reverse order", None), ] properties = [ "Colorspace", "max bpc", "aspect ratio", "Broadcast RGB", "audio", "non-desktop", "TearFree", "underscan vborder", "underscan hborder", "underscan", "scaling mode", ] help_text = """ Usage: autorandr [options] -h, --help get this small help -c, --change automatically load the first detected profile -d, --default <profile> make profile <profile> the default profile -l, --load <profile> load profile <profile> -s, --save <profile> save your current setup to profile <profile> -r, --remove <profile> remove profile <profile> --batch run autorandr for all users with active X11 sessions --current only list current (active) configuration(s) --config dump your current xrandr setup --cycle automatically load the next detected profile --debug enable verbose output --detected only list detected (available) configuration(s) --dry-run don't change anything, only print the xrandr commands --fingerprint fingerprint your current hardware setup --ignore-lid treat outputs as connected even if their lids are closed --match-edid match displays based on edid instead of name --force force (re)loading of a profile / overwrite exiting files --list list configurations --skip-options <option> comma separated list of xrandr arguments (e.g. "gamma") to skip both in detecting changes and applying a profile --version show version information and exit If no suitable profile can be identified, the current configuration is kept. To change this behaviour and switch to a fallback configuration, specify --default <profile>. autorandr supports a set of per-profile and global hooks. See the documentation for details. The following virtual configurations are available: """.strip() class Version(object): def __init__(self, version): self._version = version self._version_parts = re.split("([0-9]+)", version) def __eq__(self, other): return self._version_parts == other._version_parts def __lt__(self, other): for my, theirs in zip(self._version_parts, other._version_parts): if my.isnumeric() and theirs.isnumeric(): my = int(my) theirs = int(theirs) if my < theirs: return True return len(theirs) > len(my) def __ge__(self, other): return not (self < other) def __ne__(self, other): return not (self == other) def __le__(self, other): return (self < other) or (self == other) def __gt__(self, other): return self >= other and not (self == other) def is_closed_lid(output): if not re.match(r'(eDP(-?[0-9]\+)*|LVDS(-?[0-9]\+)*)', output): return False lids = glob.glob("/proc/acpi/button/lid/*/state") if len(lids) == 1: state_file = lids[0] with open(state_file) as f: content = f.read() return "close" in content return False class AutorandrException(Exception): def __init__(self, message, original_exception=None, report_bug=False): self.message = message self.report_bug = report_bug if original_exception: self.original_exception = original_exception trace = sys.exc_info()[2] while trace.tb_next: trace = trace.tb_next self.line = trace.tb_lineno self.file_name = trace.tb_frame.f_code.co_filename else: try: import inspect frame = inspect.currentframe().f_back self.line = frame.f_lineno self.file_name = frame.f_code.co_filename except: self.line = None self.file_name = None self.original_exception = None if os.path.abspath(self.file_name) == os.path.abspath(sys.argv[0]): self.file_name = None def __str__(self): retval = [self.message] if self.line: retval.append(" (line %d%s)" % (self.line, ("; %s" % self.file_name) if self.file_name else "")) if self.original_exception: 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:" "\nhttps://github.com/phillipberndt/autorandr/issues" "\nPlease attach the output of `xrandr --verbose` to your bug report if appropriate.") return "".join(retval) class XrandrOutput(object): "Represents an XRandR output" XRANDR_PROPERTIES_REGEXP = "|".join( [r"{}:\s*(?P<{}>[\S ]*\S+)" .format(re.sub(r"\s", r"\\\g<0>", p), re.sub(r"\W+", "_", p.lower())) for p in properties]) # This regular expression is used to parse an output in `xrandr --verbose' XRANDR_OUTPUT_REGEXP = r"""(?x) ^\s*(?P<output>\S[^ ]*)\s+ # Line starts with output name (?: # Differentiate disconnected and connected disconnected | # in first line unknown\ connection | (?P<connected>connected) ) \s* (?P<primary>primary\ )? # Might be primary screen (?:\s* (?P<width>[0-9]+)x(?P<height>[0-9]+) # Resolution (might be overridden below!) \+(?P<x>-?[0-9]+)\+(?P<y>-?[0-9]+)\s+ # Position (?:\(0x[0-9a-fA-F]+\)\s+)? # XID (?P<rotate>(?:normal|left|right|inverted))\s+ # Rotation (?:(?P<reflect>X\ and\ Y|X|Y)\ axis)? # Reflection )? # .. but only if the screen is in use. (?:[\ \t]*\([^\)]+\))(?:\s*[0-9]+mm\sx\s[0-9]+mm)? (?:[\ \t]*panning\ (?P<panning>[0-9]+x[0-9]+\+[0-9]+\+[0-9]+))? # Panning information (?:[\ \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>(?:inf|-?[0-9\.\-: e])+) | # Gamma value CRTC:\s*(?P<crtc>[0-9]) | # CRTC value Transform: (?P<transform>(?:[\-0-9\. ]+\s+){3}) | # Transformation matrix filter:\s+(?P<filter>bilinear|nearest) | # Transformation filter EDID: (?P<edid>\s*?(?:\n\t\t[0-9a-f]+)+) | # EDID of the output """ + XRANDR_PROPERTIES_REGEXP + r""" | # Properties to include in the profile (?![0-9])[^:\s][^:\n]+:.*(?:\s\t[\t ].+)* # Other properties ))+ \s* (?P<modes>(?: (?P<mode_name>\S+).+?\*current.*\s+ # Interesting (current) resolution: h:\s+width\s+(?P<mode_width>[0-9]+).+\s+ # Extract rate 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 = r"""(?x) (?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 = { "transform": "1,0,0,0,1,0,0,0,1", "panning": "0x0", } XRANDR_12_DEFAULTS = { "reflect": "normal", "rotate": "normal", "gamma": "1.0:1.0:1.0", } 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, self.fingerprint, " ".join(self.option_vector)) @property def short_edid(self): return ("%s..%s" % (self.edid[:5], self.edid[-5:])) if self.edid else "" @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(self.XRANDR_13_DEFAULTS) if xrandr_version() >= Version("1.2"): options.update(self.XRANDR_12_DEFAULTS) options.update(self.options) if "set" in self.ignored_options: options = {a: b for a, b in options.items() if not a.startswith("x-prop")} 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" options = {a: b for a, b in self.options.items() if a not in self.ignored_options} if "set" in self.ignored_options: options = {a: b for a, b in options.items() if not a.startswith("x-prop")} return options @property def option_vector(self): "Return the command line parameters for XRandR for this instance" args = ["--output", self.output] for option, arg in sorted(self.options_with_defaults.items()): if option.startswith("x-prop-"): prop_found = False for prop, xrandr_prop in [(re.sub(r"\W+", "_", p.lower()), p) for p in properties]: if prop == option[7:]: args.append("--set") args.append(xrandr_prop) prop_found = True break if not prop_found: print("Warning: Unknown property `%s' in config file. Skipping." % option[7:], file=sys.stderr) continue elif option.startswith("x-"): print("Warning: Unknown option `%s' in config file. Skipping." % option, file=sys.stderr) continue else: args.append("--%s" % option) if arg: args.append(arg) return args @property def option_string(self): "Return the command line parameters in the configuration file format" options = ["output %s" % self.output] for option, arg in sorted(self.filtered_options.items()): if arg: options.append("%s %s" % (option, arg)) else: options.append(option) return "\n".join(options) @property 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")) else: x, y = 0, 0 return x + 10000 * y def __init__(self, output, edid, options): "Instantiate using output name, edid and a dictionary of XRandR command line parameters" self.output = output self.edid = edid self.options = options self.ignored_options = [] self.parse_serial_from_edid() self.remove_default_option_values() def parse_serial_from_edid(self): self.serial = None if self.edid: if self.EDID_UNAVAILABLE in self.edid: return if "*" in self.edid: return # Thx to pyedid project, the following code was # copied (and modified) from pyedid/__init__py:21 [parse_edid()] raw = bytes.fromhex(self.edid) # Check EDID header, and checksum if raw[:8] != b'\x00\xff\xff\xff\xff\xff\xff\x00' or sum(raw) % 256 != 0: return serial_no = int.from_bytes(raw[15:11:-1], byteorder='little') serial_text = None # Offsets of standard timing information descriptors 1-4 # (see https://en.wikipedia.org/wiki/Extended_Display_Identification_Data#EDID_1.4_data_format) for timing_bytes in (raw[54:72], raw[72:90], raw[90:108], raw[108:126]): if timing_bytes[0:2] == b'\x00\x00': timing_type = timing_bytes[3] if timing_type == 0xFF: buffer = timing_bytes[5:] buffer = buffer.partition(b'\x0a')[0] serial_text = buffer.decode('cp437') self.serial = serial_text if serial_text else "0x{:x}".format(serial_no) if serial_no != 0 else None 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 superfluous" if "off" in self.options and len(self.options.keys()) > 1: self.options = {"off": None} return for option, default_value in self.XRANDR_DEFAULTS.items(): if option in self.options and self.options[option] == default_value: del self.options[option] @classmethod def from_xrandr_output(cls, xrandr_output): """Instantiate an XrandrOutput from the output of `xrandr --verbose' This method also returns a list of modes supported by the output. """ try: xrandr_output = xrandr_output.replace("\r\n", "\n") match_object = re.search(XrandrOutput.XRANDR_OUTPUT_REGEXP, xrandr_output) except: raise AutorandrException("Parsing XRandR output failed, there is an error in the regular expression.", report_bug=True) if not match_object: debug = debug_regexp(XrandrOutput.XRANDR_OUTPUT_REGEXP, xrandr_output) raise AutorandrException("Parsing XRandR output failed, the regular expression did not match: %s" % debug, report_bug=True) remainder = xrandr_output[len(match_object.group(0)):] if remainder: raise AutorandrException("Parsing XRandR output failed, %d bytes left unmatched after " "regular expression, starting at byte %d with ..'%s'." % (len(remainder), len(match_object.group(0)), remainder[:10]), report_bug=True) match = match_object.groupdict() modes = [] if match["modes"]: modes = [] for mode_match in re.finditer(XrandrOutput.XRANDR_OUTPUT_MODES_REGEXP, match["modes"]): if mode_match.group("name"): modes.append(mode_match.groupdict()) if not modes: raise AutorandrException("Parsing XRandR output failed, couldn't find any display modes", report_bug=True) options = {} if not match["connected"]: edid = None elif match["edid"]: edid = "".join(match["edid"].strip().split()) else: edid = "%s-%s" % (XrandrOutput.EDID_UNAVAILABLE, match["output"]) # An output can be disconnected but still have a mode configured. This can only happen # as a residual situation after a disconnect, you cannot associate a mode with an disconnected # output. # # This code needs to be careful not to mix the two. An output should only be configured to # "off" if it doesn't have a mode associated with it, which is modelled as "not a width" here. if not match["width"]: options["off"] = None else: 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"): options["mode"] = "%sx%s" % (match["width"] or 0, match["height"] or 0) else: options["mode"] = "%sx%s" % (match["height"] or 0, match["width"] or 0) if match["rotate"]: options["rotate"] = match["rotate"] if match["primary"]: options["primary"] = None if match["reflect"] == "X": options["reflect"] = "x" elif match["reflect"] == "Y": options["reflect"] = "y" elif match["reflect"] == "X and Y": options["reflect"] = "xy" if match["x"] or match["y"]: options["pos"] = "%sx%s" % (match["x"] or "0", match["y"] or "0") 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": options["transform"] = transformation 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["filter"]: options["filter"] = match["filter"] 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["crtc"]: options["crtc"] = match["crtc"] if match["rate"]: options["rate"] = match["rate"] for prop in [re.sub(r"\W+", "_", p.lower()) for p in properties]: if match[prop]: options["x-prop-" + prop] = match[prop] return XrandrOutput(match["output"], edid, options), modes @classmethod def from_config_file(cls, profile, edid_map, configuration): "Instantiate an XrandrOutput from the contents of a configuration file" options = {} for line in configuration.split("\n"): if line: line = line.split(None, 1) if line and line[0].startswith("#"): continue options[line[0]] = line[1] if len(line) > 1 else None edid = None if options["output"] in edid_map: edid = edid_map[options["output"]] else: # This fuzzy matching is for legacy autorandr that used sysfs output names fuzzy_edid_map = [re.sub("(card[0-9]+|-)", "", x) for x in edid_map.keys()] fuzzy_output = re.sub("(card[0-9]+|-)", "", options["output"]) if fuzzy_output in fuzzy_edid_map: edid = edid_map[list(edid_map.keys())[fuzzy_edid_map.index(fuzzy_output)]] elif "off" not in options: raise AutorandrException("Profile `%s': Failed to find an EDID for output `%s' in setup file, required " "as `%s' is not off in config file." % (profile, options["output"], options["output"])) output = options["output"] del options["output"] return XrandrOutput(output, edid, options) @property def fingerprint(self): return str(self.serial) if self.serial else self.short_edid def fingerprint_equals(self, other): if self.serial and other.serial: return self.serial == other.serial else: return self.edid_equals(other) 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 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 and not self.edid.startswith(XrandrOutput.EDID_UNAVAILABLE): return hashlib.md5(binascii.unhexlify(self.edid)).hexdigest() == other.edid if "*" in self.edid: return match_asterisk(self.edid, other.edid) > 0 elif "*" in other.edid: return match_asterisk(other.edid, self.edid) > 0 return self.edid == other.edid def __ne__(self, other): return not (self == other) def __eq__(self, other): return self.fingerprint_equals(other) and self.output == other.output and self.filtered_options == other.filtered_options def verbose_diff(self, other): "Compare to another XrandrOutput and return a list of human readable differences" diffs = [] if not self.fingerprint_equals(other): diffs.append("EDID `%s' differs from `%s'" % (self.fingerprint, other.fingerprint)) if self.output != other.output: diffs.append("Output name `%s' differs from `%s'" % (self.output, other.output)) if "off" in self.options and "off" not in other.options: diffs.append("The output is disabled currently, but active in the new configuration") elif "off" in other.options and "off" not in self.options: diffs.append("The output is currently enabled, but inactive in the new configuration") else: for name in set(chain.from_iterable((self.options.keys(), other.options.keys()))): if name not in other.options: diffs.append("Option --%s %sis not present in the new configuration" % (name, "(= `%s') " % self.options[name] if self.options[name] else "")) elif name not in self.options: diffs.append("Option --%s (`%s' in the new configuration) is not present currently" % (name, other.options[name])) elif self.options[name] != other.options[name]: diffs.append("Option --%s %sis `%s' in the new configuration" % (name, "(= `%s') " % self.options[name] if self.options[name] else "", other.options[name])) return diffs 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() try: version = re.search(r"xrandr program version\s+([0-9\.]+)", version_string).group(1) xrandr_version.version = Version(version) except AttributeError: xrandr_version.version = Version("1.3.0") 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: import regex bounds = (0, len(string)) while bounds[0] != bounds[1]: half = int((bounds[0] + bounds[1]) / 2) if half == bounds[0]: break bounds = (half, bounds[1]) if regex.search(pattern, string[:half], partial=True) else (bounds[0], half - 1) partial_length = bounds[0] return ("Regular expression matched until position %d, ..'%s', and did not match from '%s'.." % (partial_length, string[max(0, partial_length - 20):partial_length], string[partial_length:partial_length + 10])) except ImportError: pass return "Debug information would be available if the `regex' module was installed." def parse_xrandr_output( *, ignore_lid, ): "Parse the output of `xrandr --verbose' into a list of outputs" xrandr_output = os.popen("xrandr -q --verbose").read() if not xrandr_output: raise AutorandrException("Failed to run xrandr") # We are not interested in screens xrandr_output = re.sub("(?m)^Screen [0-9].+", "", xrandr_output).strip() # Split at output boundaries and instantiate an XrandrOutput per output split_xrandr_output = re.split("(?m)^([^ ]+ (?:(?:dis)?connected|unknown connection).*)$", xrandr_output) if len(split_xrandr_output) < 2: raise AutorandrException("No output boundaries found", report_bug=True) outputs = OrderedDict() modes = OrderedDict() for i in range(1, len(split_xrandr_output), 2): output_name = split_xrandr_output[i].split()[0] output, output_modes = XrandrOutput.from_xrandr_output("".join(split_xrandr_output[i:i + 2])) outputs[output_name] = output if output_modes: modes[output_name] = output_modes # consider a closed lid as disconnected if other outputs are connected if not ignore_lid and sum( o.edid != None for o in outputs.values() ) > 1: for output_name in outputs.keys(): if is_closed_lid(output_name): outputs[output_name].edid = None return outputs, modes def load_profiles(profile_path): "Load the stored profiles" profiles = {} for profile in os.listdir(profile_path): config_name = os.path.join(profile_path, profile, "config") setup_name = os.path.join(profile_path, profile, "setup") if not os.path.isfile(config_name) or not os.path.isfile(setup_name): continue edids = dict([x.split() for x in (y.strip() for y in open(setup_name).readlines()) if x and x[0] != "#"]) config = {} buffer = [] for line in chain(open(config_name).readlines(), ["output"]): if line[:6] == "output" and buffer: config[buffer[0].strip().split()[-1]] = XrandrOutput.from_config_file(profile, edids, "".join(buffer)) buffer = [line] else: buffer.append(line) for output_name in list(config.keys()): if config[output_name].edid is None: del config[output_name] profiles[profile] = { "config": config, "path": os.path.join(profile_path, profile), "config-mtime": os.stat(config_name).st_mtime, } return profiles def get_symlinks(profile_path): "Load all symlinks from a directory" symlinks = {} for link in os.listdir(profile_path): file_name = os.path.join(profile_path, link) if os.path.islink(file_name): symlinks[link] = os.readlink(file_name) return symlinks def match_asterisk(pattern, data): """Match data against a pattern The difference to fnmatch is that this function only accepts patterns with a single asterisk and that it returns a "closeness" number, which is larger the better the match. Zero indicates no match at all. """ if "*" not in pattern: return 1 if pattern == data else 0 parts = pattern.split("*") if len(parts) > 2: raise ValueError("Only patterns with a single asterisk are supported, %s is invalid" % pattern) if not data.startswith(parts[0]): return 0 if not data.endswith(parts[1]): return 0 matched = len(pattern) total = len(data) + 1 return matched * 1. / total def update_profiles_edid(profiles, config): fp_map = {} for c in config: if config[c].fingerprint is not None: fp_map[config[c].fingerprint] = c for p in profiles: profile_config = profiles[p]["config"] for fingerprint in fp_map: for c in list(profile_config.keys()): if profile_config[c].fingerprint != fingerprint or c == fp_map[fingerprint]: continue print("%s: renaming display %s to %s" % (p, c, fp_map[fingerprint]), file=sys.stderr) tmp_disp = profile_config[c] if fp_map[fingerprint] in profile_config: # Swap the two entries profile_config[c] = profile_config[fp_map[fingerprint]] profile_config[c].output = c else: # Object is reassigned to another key, drop this one del profile_config[c] profile_config[fp_map[fingerprint]] = tmp_disp profile_config[fp_map[fingerprint]].output = fp_map[fingerprint] def find_profiles(current_config, profiles): "Find profiles matching the currently connected outputs, sorting asterisk matches to the back" detected_profiles = [] for profile_name, profile in profiles.items(): config = profile["config"] matches = True if not config.items(): continue for name, output in config.items(): if not output.fingerprint: continue if name not in current_config or not output.fingerprint_equals(current_config[name]): matches = False break if not matches or any((name not in config.keys() for name in current_config.keys() if current_config[name].fingerprint)): continue if matches: closeness = max(match_asterisk(output.edid, current_config[name].edid), match_asterisk( current_config[name].edid, output.edid)) detected_profiles.append((closeness, profile_name)) detected_profiles = [o[1] for o in sorted(detected_profiles, key=lambda x: -x[0])] return detected_profiles def profile_blocked(profile_path, meta_information=None): """Check if a profile is blocked. meta_information is expected to be an dictionary. It will be passed to the block scripts in the environment, as variables called AUTORANDR_<CAPITALIZED_KEY_HERE>. """ return not exec_scripts(profile_path, "block", meta_information) def check_configuration_pre_save(configuration): "Check that a configuration is safe for saving." outputs = sorted(configuration.keys(), key=lambda x: configuration[x].sort_key) for output in outputs: if "off" not in configuration[output].options and not configuration[output].edid: return ("`%(o)s' is not off (has a mode configured) but is disconnected (does not have an EDID).\n" "This typically means that it has been recently unplugged and then not properly disabled\n" "by the user. Please disable it (e.g. using `xrandr --output %(o)s --off`) and then rerun\n" "this command.") % {"o": output} def output_configuration(configuration, config): "Write a configuration file" outputs = sorted(configuration.keys(), key=lambda x: configuration[x].sort_key) for output in outputs: print(configuration[output].option_string, file=config) def output_setup(configuration, setup): "Write a setup (fingerprint) file" outputs = sorted(configuration.keys()) for output in outputs: if configuration[output].edid: print(output, configuration[output].edid, file=setup) def save_configuration(profile_path, profile_name, configuration, forced=False): "Save a configuration into a profile" if not os.path.isdir(profile_path): os.makedirs(profile_path) config_path = os.path.join(profile_path, "config") setup_path = os.path.join(profile_path, "setup") if os.path.isfile(config_path) and not forced: raise AutorandrException('Refusing to overwrite config "{}" without passing "--force"!'.format(profile_name)) if os.path.isfile(setup_path) and not forced: raise AutorandrException('Refusing to overwrite config "{}" without passing "--force"!'.format(profile_name)) with open(config_path, "w") as config: output_configuration(configuration, config) with open(setup_path, "w") as setup: output_setup(configuration, setup) def update_mtime(filename): "Update a file's mtime" try: os.utime(filename, None) return True except: return False def call_and_retry(*args, **kwargs): """Wrapper around subprocess.call that retries failed calls. This function calls subprocess.call and on non-zero exit states, waits a second and then retries once. This mitigates #47, a timing issue with some drivers. """ if kwargs.pop("dry_run", False): for arg in args[0]: print(shlex.quote(arg), end=" ") print() return 0 else: if hasattr(subprocess, "DEVNULL"): kwargs["stdout"] = getattr(subprocess, "DEVNULL") else: kwargs["stdout"] = open(os.devnull, "w") kwargs["stderr"] = kwargs["stdout"] retval = subprocess.call(*args, **kwargs) if retval != 0: time.sleep(1) retval = subprocess.call(*args, **kwargs) return retval def get_fb_dimensions(configuration): width = 0 height = 0 for output in configuration.values(): if "off" in output.options or not output.edid: continue # This won't work with all modes -- but it's a best effort. match = re.search("[0-9]{3,}x[0-9]{3,}", output.options["mode"]) if not match: return None o_mode = match.group(0) o_width, o_height = map(int, o_mode.split("x")) if "transform" in output.options: a, b, c, d, e, f, g, h, i = map(float, output.options["transform"].split(",")) w = (g * o_width + h * o_height + i) x = (a * o_width + b * o_height + c) / w y = (d * o_width + e * o_height + f) / w o_width, o_height = x, y if "rotate" in output.options: if output.options["rotate"] in ("left", "right"): o_width, o_height = o_height, o_width if "pos" in output.options: o_left, o_top = map(int, output.options["pos"].split("x")) o_width += o_left o_height += o_top if "panning" in output.options: match = re.match(r"(?P<w>[0-9]+)x(?P<h>[0-9]+)(?:\+(?P<x>[0-9]+))?(?:\+(?P<y>[0-9]+))?.*", output.options["panning"]) if match: detail = match.groupdict(default="0") o_width = int(detail.get("w")) + int(detail.get("x")) o_height = int(detail.get("h")) + int(detail.get("y")) width = max(width, o_width) height = max(height, o_height) return math.ceil(width), math.ceil(height) def apply_configuration(new_configuration, current_configuration, dry_run=False): "Apply a configuration" found_top_left_monitor = False found_left_monitor = False found_top_monitor = False outputs = sorted(new_configuration.keys(), key=lambda x: new_configuration[x].sort_key) base_argv = ["xrandr"] # 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.) # - Some implementations can not handle --transform at all, so avoid it unless # necessary. (See https://github.com/phillipberndt/autorandr/issues/37) # - Some implementations can not handle --panning without specifying --fb # explicitly, so avoid it unless necessary. # (See https://github.com/phillipberndt/autorandr/issues/72) fb_dimensions = get_fb_dimensions(new_configuration) try: fb_args = ["--fb", "%dx%d" % fb_dimensions] except: # Failed to obtain frame-buffer size. Doesn't matter, xrandr will choose for the user. fb_args = [] auxiliary_changes_pre = [] disable_outputs = [] enable_outputs = [] remain_active_count = 0 for output in outputs: if not new_configuration[output].edid or "off" in new_configuration[output].options: disable_outputs.append(new_configuration[output].option_vector) else: if output not in current_configuration: raise AutorandrException("New profile configures output %s which does not exist in current xrandr --verbose output. " "Don't know how to proceed." % output) 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 if not found_top_left_monitor: position = new_configuration[output].options.get("pos", "0x0") if position == "0x0": found_top_left_monitor = True enable_outputs.insert(0, option_vector) elif not found_left_monitor and position.startswith("0x"): found_left_monitor = True enable_outputs.insert(0, option_vector) elif not found_top_monitor and position.endswith("x0"): found_top_monitor = True enable_outputs.insert(0, option_vector) else: enable_outputs.append(option_vector) else: 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(map(shlex.quote, argv))) # Starting here, fix the frame buffer size # Do not do this earlier, as disabling scaling might temporarily make the framebuffer # dimensions larger than they will finally be. base_argv += fb_args # 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']) # If we did not find a candidate, we might need to inject a call # If there is no output to disable, we will enable 0x and x0 at the same time if not found_top_left_monitor and len(disable_outputs) > 0: # If the call to 0x and x0 is split, inject one of them if found_top_monitor and found_left_monitor: enable_outputs.insert(0, enable_outputs[0]) # 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(map(shlex.quote, argv))) # Adjust the frame buffer to match (see #319) if fb_args: argv = base_argv if call_and_retry(argv, dry_run=dry_run) != 0: raise AutorandrException("Command failed: %s" % " ".join(map(shlex.quote, 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 and "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[output].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", "horizontal-reverse", "vertical-reverse"): shift = 0 if profile_name.startswith("horizontal"): shift_index = "width" pos_specifier = "%sx0" else: shift_index = "height" pos_specifier = "0x%s" config_iter = reversed(configuration) if "reverse" in profile_name else iter(configuration) for output in config_iter: 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("\\-") def exit_help(): "Print help and exit" print(help_text) for profile in virtual_profiles: name, description = profile[:2] description = [description] max_width = 78 - 18 while len(description[0]) > max_width + 1: left_over = description[0][max_width:] description[0] = description[0][:max_width] + "-" description.insert(1, " %-15s %s" % ("", left_over)) description = "\n".join(description) print(" %-15s %s" % (name, description)) sys.exit(0) def exec_scripts(profile_path, script_name, meta_information=None): """"Run userscripts This will run all executables from the profile folder, and global per-user and system-wide configuration folders, named script_name or residing in subdirectories named script_name.d. If profile_path is None, only global scripts will be invoked. meta_information is expected to be an dictionary. It will be passed to the block scripts in the environment, as variables called AUTORANDR_<CAPITALIZED_KEY_HERE>. Returns True unless any of the scripts exited with non-zero exit status. """ all_ok = True env = os.environ.copy() if meta_information: for key, value in meta_information.items(): env["AUTORANDR_{}".format(key.upper())] = str(value) # If there are multiple candidates, the XDG spec tells to only use the first one. ran_scripts = set() user_profile_path = os.path.expanduser("~/.autorandr") if not os.path.isdir(user_profile_path): user_profile_path = os.path.join(os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), "autorandr") candidate_directories = [] if profile_path: candidate_directories.append(profile_path) candidate_directories.append(user_profile_path) for config_dir in os.environ.get("XDG_CONFIG_DIRS", "/etc/xdg").split(":"): candidate_directories.append(os.path.join(config_dir, "autorandr")) for folder in candidate_directories: if script_name not in ran_scripts: script = os.path.join(folder, script_name) if os.access(script, os.X_OK | os.F_OK): try: all_ok &= subprocess.call(script, env=env) != 0 except Exception as e: raise AutorandrException("Failed to execute user command: %s. Error: %s" % (script, str(e))) ran_scripts.add(script_name) script_folder = os.path.join(folder, "%s.d" % script_name) if os.access(script_folder, os.R_OK | os.X_OK) and os.path.isdir(script_folder): for file_name in sorted(os.listdir(script_folder)): check_name = "d/%s" % (file_name,) if check_name not in ran_scripts: script = os.path.join(script_folder, file_name) if os.access(script, os.X_OK | os.F_OK): try: all_ok &= subprocess.call(script, env=env) != 0 except Exception as e: raise AutorandrException("Failed to execute user command: %s. Error: %s" % (script, str(e))) ran_scripts.add(check_name) return all_ok def dispatch_call_to_sessions(argv): """Invoke autorandr for each open local X11 session with the given options. The function iterates over all processes not owned by root and checks whether they have DISPLAY and XAUTHORITY variables set. It strips the screen from any variable it finds (i.e. :0.0 becomes :0) and checks whether this display has been handled already. If it has not, it forks, changes uid/gid to the user owning the process, reuses the process's environment and runs autorandr with the parameters from argv. This function requires root permissions. It only works for X11 servers that have at least one non-root process running. It is susceptible for attacks where one user runs a process with another user's DISPLAY variable - in this case, it might happen that autorandr is invoked for the other user, which won't work. Since no other harm than prevention of automated execution of autorandr can be done this way, the assumption is that in this situation, the local administrator will handle the situation.""" X11_displays_done = set() autorandr_binary = os.path.abspath(argv[0]) backup_candidates = {} def fork_child_autorandr(pwent, process_environ): print("Running autorandr as %s for display %s" % (pwent.pw_name, process_environ["DISPLAY"])) child_pid = os.fork() if child_pid == 0: # This will throw an exception if any of the privilege changes fails, # so it should be safe. Also, note that since the environment # is taken from a process owned by the user, reusing it should # not leak any information. try: os.setgroups(os.getgrouplist(pwent.pw_name, pwent.pw_gid)) except AttributeError: # Python 2 doesn't have getgrouplist os.setgroups([]) os.setresgid(pwent.pw_gid, pwent.pw_gid, pwent.pw_gid) os.setresuid(pwent.pw_uid, pwent.pw_uid, pwent.pw_uid) os.chdir(pwent.pw_dir) os.environ.clear() os.environ.update(process_environ) if sys.executable != "" and sys.executable != None: os.execl(sys.executable, sys.executable, autorandr_binary, *argv[1:]) else: os.execl(autorandr_binary, autorandr_binary, *argv[1:]) sys.exit(1) os.waitpid(child_pid, 0) # The following line assumes that user accounts start at 1000 and that no # one works using the root or another system account. This is rather # restrictive, but de facto default. If this breaks your use case, set the # env var AUTORANDR_UID_MIN as appropriate. (Alternatives would be to use # the UID_MIN from /etc/login.defs or FIRST_UID from /etc/adduser.conf; but # effectively, both values aren't binding in any way.) uid_min = 1000 if 'AUTORANDR_UID_MIN' in os.environ: uid_min = int(os.environ['AUTORANDR_UID_MIN']) for directory in os.listdir("/proc"): directory = os.path.join("/proc/", directory) if not os.path.isdir(directory): continue environ_file = os.path.join(directory, "environ") if not os.path.isfile(environ_file): continue uid = os.stat(environ_file).st_uid if uid < uid_min: continue process_environ = {} for environ_entry in open(environ_file, 'rb').read().split(b"\0"): try: environ_entry = environ_entry.decode("ascii") except UnicodeDecodeError: continue name, sep, value = environ_entry.partition("=") if name and sep: if name == "DISPLAY" and "." in value: value = value[:value.find(".")] process_environ[name] = value if "DISPLAY" not in process_environ: # Cannot work with this environment, skip. continue if "WAYLAND_DISPLAY" in process_environ and process_environ["WAYLAND_DISPLAY"]: if "--debug" in argv: print("Detected Wayland session '{0}'. Skipping.".format(process_environ["WAYLAND_DISPLAY"])) continue # To allow scripts to detect batch invocation (especially useful for predetect) process_environ["AUTORANDR_BATCH_PID"] = str(os.getpid()) process_environ["UID"] = str(uid) display = process_environ["DISPLAY"] if "XAUTHORITY" not in process_environ: # It's very likely that we cannot work with this environment either, # but keep it as a backup just in case we don't find anything else. backup_candidates[display] = process_environ continue if display not in X11_displays_done: try: pwent = pwd.getpwuid(uid) except KeyError: # User has no pwd entry continue fork_child_autorandr(pwent, process_environ) X11_displays_done.add(display) # Run autorandr for any users/displays which didn't have a process with # XAUTHORITY set. for display, process_environ in backup_candidates.items(): if display not in X11_displays_done: try: pwent = pwd.getpwuid(int(process_environ["UID"])) except KeyError: # User has no pwd entry continue fork_child_autorandr(pwent, process_environ) X11_displays_done.add(display) def enabled_monitors(config): monitors = [] for monitor in config: if "--off" in config[monitor].option_vector: continue monitors.append(monitor) return monitors def read_config(options, directory): """Parse a configuration config.ini from directory and merge it into the options dictionary""" config = configparser.ConfigParser() config.read(os.path.join(directory, "settings.ini")) if config.has_section("config"): for key, value in config.items("config"): options.setdefault("--%s" % key, value) def main(argv): try: opts, args = getopt.getopt( argv[1:], "s:r:l:d:cfh", [ "batch", "dry-run", "change", "cycle", "default=", "save=", "remove=", "load=", "force", "fingerprint", "config", "debug", "skip-options=", "help", "list", "current", "detected", "version", "match-edid", "ignore-lid" ] ) except getopt.GetoptError as e: print("Failed to parse options: {0}.\n" "Use --help to get usage information.".format(str(e)), file=sys.stderr) sys.exit(posix.EX_USAGE) options = dict(opts) if "-h" in options or "--help" in options: exit_help() if "--version" in options: print("autorandr " + __version__) sys.exit(0) if "--current" in options and "--detected" in options: print("--current and --detected are mutually exclusive.", file=sys.stderr) sys.exit(posix.EX_USAGE) # Batch mode if "--batch" in options: if ("DISPLAY" not in os.environ or not os.environ["DISPLAY"]) and os.getuid() == 0: dispatch_call_to_sessions([x for x in argv if x != "--batch"]) else: print("--batch mode can only be used by root and if $DISPLAY is unset") return if "AUTORANDR_BATCH_PID" in os.environ: user = pwd.getpwuid(os.getuid()) user = user.pw_name if user else "#%d" % os.getuid() print("autorandr running as user %s (started from batch instance)" % user) if ("WAYLAND_DISPLAY" in os.environ and os.environ["WAYLAND_DISPLAY"]): print("Detected Wayland session '{0}'. Exiting.".format(os.environ["WAYLAND_DISPLAY"]), file=sys.stderr) sys.exit(1) profiles = {} profile_symlinks = {} try: # Load profiles from each XDG config directory # The XDG spec says that earlier entries should take precedence, so reverse the order for directory in reversed(os.environ.get("XDG_CONFIG_DIRS", "/etc/xdg").split(":")): system_profile_path = os.path.join(directory, "autorandr") if os.path.isdir(system_profile_path): profiles.update(load_profiles(system_profile_path)) profile_symlinks.update(get_symlinks(system_profile_path)) read_config(options, system_profile_path) # For the user's profiles, prefer the legacy ~/.autorandr if it already exists # profile_path is also used later on to store configurations profile_path = os.path.expanduser("~/.autorandr") if not os.path.isdir(profile_path): # Elsewise, follow the XDG specification profile_path = os.path.join(os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), "autorandr") if os.path.isdir(profile_path): profiles.update(load_profiles(profile_path)) profile_symlinks.update(get_symlinks(profile_path)) read_config(options, profile_path) except Exception as e: raise AutorandrException("Failed to load profiles", e) exec_scripts(None, "predetect") ignore_lid = "--ignore-lid" in options config, modes = parse_xrandr_output( ignore_lid=ignore_lid, ) if "--match-edid" in options: update_profiles_edid(profiles, config) # Sort by mtime sort_direction = -1 if "--cycle" in options: # When cycling through profiles, put the profile least recently used to the top of the list sort_direction = 1 profiles = OrderedDict(sorted(profiles.items(), key=lambda x: sort_direction * x[1]["config-mtime"])) profile_symlinks = {k: v for k, v in profile_symlinks.items() if v in (x[0] for x in virtual_profiles) or v in profiles} if "--fingerprint" in options: output_setup(config, sys.stdout) sys.exit(0) if "--config" in options: 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: if options["--save"] in (x[0] for x in virtual_profiles): raise AutorandrException("Cannot save current configuration as profile '%s':\n" "This configuration name is a reserved virtual configuration." % options["--save"]) error = check_configuration_pre_save(config) if error: print("Cannot save current configuration as profile '%s':" % options["--save"]) print(error) sys.exit(1) try: profile_folder = os.path.join(profile_path, options["--save"]) save_configuration(profile_folder, options['--save'], config, forced="--force" in options) exec_scripts(profile_folder, "postsave", { "CURRENT_PROFILE": options["--save"], "PROFILE_FOLDER": profile_folder, "MONITORS": ":".join(enabled_monitors(config)), }) except AutorandrException as e: raise e except Exception as e: raise AutorandrException("Failed to save current configuration as profile '%s'" % (options["--save"],), e) print("Saved current configuration as profile '%s'" % options["--save"]) sys.exit(0) if "-r" in options: options["--remove"] = options["-r"] if "--remove" in options: if options["--remove"] in (x[0] for x in virtual_profiles): raise AutorandrException("Cannot remove profile '%s':\n" "This configuration name is a reserved virtual configuration." % options["--remove"]) if options["--remove"] not in profiles.keys(): raise AutorandrException("Cannot remove profile '%s':\n" "This profile does not exist." % options["--remove"]) try: remove = True profile_folder = os.path.join(profile_path, options["--remove"]) profile_dirlist = os.listdir(profile_folder) profile_dirlist.remove("config") profile_dirlist.remove("setup") if profile_dirlist: print("Profile folder '%s' contains the following additional files:\n" "---\n%s\n---" % (options["--remove"], "\n".join(profile_dirlist))) response = input("Do you really want to remove profile '%s'? If so, type 'yes': " % options["--remove"]).strip() if response != "yes": remove = False if remove is True: shutil.rmtree(profile_folder) print("Removed profile '%s'" % options["--remove"]) else: print("Profile '%s' was not removed" % options["--remove"]) except Exception as e: raise AutorandrException("Failed to remove profile '%s'" % (options["--remove"],), e) sys.exit(0) detected_profiles = find_profiles(config, profiles) load_profile = False if "-l" in options: options["--load"] = options["-l"] if "--load" in options: load_profile = options["--load"] elif len(args) == 1: load_profile = args[0] else: # Find the active profile(s) first, for the block script (See #42) current_profiles = [] for profile_name in profiles.keys(): configs_are_equal = is_equal_configuration(config, profiles[profile_name]["config"]) if configs_are_equal: current_profiles.append(profile_name) block_script_metadata = { "CURRENT_PROFILE": "".join(current_profiles[:1]), "CURRENT_PROFILES": ":".join(current_profiles) } best_index = 9999 for profile_name in profiles.keys(): if profile_blocked(os.path.join(profile_path, profile_name), block_script_metadata): if not any(opt in options for opt in ("--current", "--detected", "--list")): print("%s (blocked)" % profile_name) continue props = [] is_current_profile = profile_name in current_profiles if profile_name in detected_profiles: if len(detected_profiles) == 1: index = 1 props.append("(detected)") else: index = detected_profiles.index(profile_name) + 1 props.append("(detected) (%d%s match)" % (index, ["st", "nd", "rd"][index - 1] if index < 4 else "th")) if index < best_index: if "-c" in options or "--change" in options or ("--cycle" in options and not is_current_profile): load_profile = profile_name best_index = index elif "--detected" in options: continue if is_current_profile: props.append("(current)") elif "--current" in options: continue if any(opt in options for opt in ("--current", "--detected", "--list")): print("%s" % (profile_name, )) else: print("%s%s%s" % (profile_name, " " if props else "", " ".join(props))) if not configs_are_equal and "--debug" in options and profile_name in detected_profiles: print_profile_differences(config, profiles[profile_name]["config"]) if "-d" in options: options["--default"] = options["-d"] if not load_profile and "--default" in options and ("-c" in options or "--change" in options or "--cycle" in options): load_profile = options["--default"] if load_profile: if load_profile in profile_symlinks: if "--debug" in options: print("'%s' symlinked to '%s'" % (load_profile, profile_symlinks[load_profile])) load_profile = profile_symlinks[load_profile] if load_profile in (x[0] for x in virtual_profiles): load_config = generate_virtual_profile(config, modes, load_profile) scripts_path = os.path.join(profile_path, load_profile) else: try: profile = profiles[load_profile] load_config = profile["config"] scripts_path = profile["path"] except KeyError: raise AutorandrException("Failed to load profile '%s': Profile not found" % load_profile) if "--dry-run" not in options: update_mtime(os.path.join(scripts_path, "config")) add_unused_outputs(config, load_config) if load_config == dict(config) and "-f" not in options and "--force" not in options: print("Config already loaded", file=sys.stderr) sys.exit(0) if "--debug" in options and load_config != dict(config): print("Loading profile '%s'" % load_profile) print_profile_differences(config, load_config) remove_irrelevant_outputs(config, load_config) try: if "--dry-run" in options: apply_configuration(load_config, config, True) else: script_metadata = { "CURRENT_PROFILE": load_profile, "PROFILE_FOLDER": scripts_path, "MONITORS": ":".join(enabled_monitors(load_config)), } exec_scripts(scripts_path, "preswitch", script_metadata) if "--debug" in options: print("Going to run:") apply_configuration(load_config, config, True) apply_configuration(load_config, config, False) exec_scripts(scripts_path, "postswitch", script_metadata) except AutorandrException as e: raise AutorandrException("Failed to apply profile '%s'" % load_profile, e, e.report_bug) except Exception as e: raise AutorandrException("Failed to apply profile '%s'" % load_profile, e, True) if "--dry-run" not in options and "--debug" in options: new_config, _ = parse_xrandr_output( ignore_lid=ignore_lid, ) if "--skip-options" in options: for output in new_config.values(): output.set_ignored_options(skip_options) if not is_equal_configuration(new_config, load_config): print("The configuration change did not go as expected:") print_profile_differences(new_config, load_config) sys.exit(0) def exception_handled_main(argv=sys.argv): try: main(sys.argv) except AutorandrException as e: print(e, file=sys.stderr) sys.exit(1) except Exception as e: 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 at " "https://github.com/phillipberndt/autorandr/issues.".format(e), file=sys.stderr) raise if __name__ == '__main__': exception_handled_main() 07070100000006000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000002400000000autorandr-1.15.0.1709469470/contrib07070100000007000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000003700000000autorandr-1.15.0.1709469470/contrib/autorandr_launcher07070100000008000081A400000000000000000000000165E46F1E00000014000000000000000000000000000000000000004200000000autorandr-1.15.0.1709469470/contrib/autorandr_launcher/.gitignore/autorandr-launcher 07070100000009000081A400000000000000000000000165E46F1E00001040000000000000000000000000000000000000004C00000000autorandr-1.15.0.1709469470/contrib/autorandr_launcher/autorandr_launcher.c#include <signal.h> #include <xcb/xcb.h> #include <xcb/randr.h> #include <getopt.h> #include <unistd.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <inttypes.h> #include <errno.h> #include <string.h> #ifndef AUTORANDR_PATH #define AUTORANDR_PATH "/usr/bin/autorandr" #endif // indent -kr -i8 static int VERBOSE = 0; extern char **environ; static void sigterm_handler(int signum) { signal(signum, SIG_DFL); kill(getpid(), signum); } __attribute__((format(printf, 1, 2))) static void ar_log(const char *format, ...) { va_list args; if (!VERBOSE) return; va_start(args, format); vprintf(format, args); va_end(args); fflush(stdout); } static int ar_launch(void) { static const char *argv[] = { AUTORANDR_PATH, "--change", "--default", "default", NULL}; char **comm = malloc(sizeof argv); memcpy(comm, argv, sizeof argv); pid_t pid = fork(); if (pid == 0) { if (execve(argv[0], comm, environ) == -1) { int errsv = errno; fprintf(stderr, "Error executing file: %s\n", strerror(errsv)); exit(errsv); } exit(127); } else { waitpid(pid, 0, 0); free(comm); } return 0; } int main(int argc, char **argv) { int help = 0; int version = 0; int daemonize = 0; const struct option long_options[] = { { "help", no_argument, &help, 1 }, { "daemonize", no_argument, &daemonize, 1 }, { "version", no_argument, &version, 1 }, { "verbose", no_argument, &VERBOSE, 1 }, }; static const char *short_options = "hd"; const char *help_str = "Usage: autorandr_launcher [OPTION]\n" "\n" "Listens to X server screen change events and launches autorandr after an event occurs.\n" "\n" "\t-h,--help\t\t\tDisplay this help and exit\n" "\t-d, --daemonize\t\t\tDaemonize program\n" "\t--verbose\t\t\tOutput debugging information (prevents daemonizing)\n" "\t--version\t\t\tDisplay version and exit\n"; const char *version_str = "v.5\n"; int option_index = 0; int ch = 0; while (ch != -1) { ch = getopt_long(argc, argv, short_options, long_options, &option_index); switch (ch) { case 'h': help = 1; break; case 'd': daemonize = 1; break; } } if (help == 1) { printf("%s", help_str); exit(0); } if (version == 1) { printf("%s", version_str); exit(0); } // Check for already running daemon? // Daemonize if (daemonize == 1 && VERBOSE != 1) { struct sigaction sa; sa.sa_handler = sigterm_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); signal(SIGHUP, SIG_IGN); if (daemon(0, 0)) { fprintf(stderr, "Failed to daemonize!\n"); exit(1); } } int screenNum; xcb_connection_t *c = xcb_connect(NULL, &screenNum); int conn_error = xcb_connection_has_error(c); if (conn_error) { fprintf(stderr, "Connection error!\n"); exit(conn_error); } // Get the screen whose number is screenNum const xcb_setup_t *setup = xcb_get_setup(c); xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup); // we want the screen at index screenNum of the iterator for (int i = 0; i < screenNum; ++i) { xcb_screen_next(&iter); } xcb_screen_t *default_screen = iter.data; ar_log("Connected to server\n"); // Subscribe to screen change events xcb_randr_select_input(c, default_screen->root, XCB_RANDR_NOTIFY_MASK_SCREEN_CHANGE); xcb_flush(c); xcb_timestamp_t last_timestamp = (xcb_timestamp_t) 0; time_t last_time = time(NULL); ar_log("Waiting for event\n"); xcb_generic_event_t *evt; while ( (evt = xcb_wait_for_event(c)) ) { ar_log("Event type: %" PRIu8 "\n", evt->response_type); if (evt->response_type) { xcb_randr_screen_change_notify_event_t *randr_evt = (xcb_randr_screen_change_notify_event_t *) evt; time_t evt_time = time(NULL); if ((randr_evt->timestamp > last_timestamp) && (evt_time > last_time + 1)) { ar_log("Launch autorandr!\n"); ar_launch(); last_time = evt_time; last_timestamp = randr_evt->timestamp; } } free(evt); } } 0707010000000A000081A400000000000000000000000165E46F1E00000583000000000000000000000000000000000000004000000000autorandr-1.15.0.1709469470/contrib/autorandr_launcher/makefileCFLAGS = -pipe \ -o2 \ -Wstrict-overflow=5 -fstack-protector-all \ -W -Wall -Wextra \ -Wbad-function-cast \ -Wcast-align \ -Wcast-qual \ -Wconversion \ -Wfloat-equal \ -Wformat-y2k \ -Winit-self \ -Winline \ -Winvalid-pch \ -Wmissing-declarations \ -Wmissing-field-initializers \ -Wmissing-format-attribute \ -Wmissing-include-dirs \ -Wmissing-noreturn \ -Wmissing-prototypes \ -Wnested-externs \ -Wnormalized=nfc \ -Wold-style-definition \ -Woverlength-strings \ -Wpacked \ -Wpadded \ -Wpointer-arith \ -Wredundant-decls \ -Wshadow \ -Wsign-compare \ -Wstack-protector \ -Wstrict-aliasing=2 \ -Wstrict-prototypes \ -Wundef \ -Wunsafe-loop-optimizations \ -Wvolatile-register-var \ -Wwrite-strings LAUNCHER_LDLIBS=$(shell pkg-config --libs pkg-config xcb xcb-randr 2>/dev/null) LAUNCHER_CFLAGS=$(shell pkg-config --cflags pkg-config xcb xcb-randr 2>/dev/null) USER_DEFS="-DAUTORANDR_PATH=\"$(shell which autorandr 2>/dev/null)\"" #------------------------------------------------------------------------------ .PHONY : all clean #------------------------------------------------------------------------------ all : autorandr-launcher autorandr-launcher: autorandr_launcher.c $(CC) $(CFLAGS) $(LAUNCHER_CFLAGS) $(USER_DEFS) -o $@ $+ $(LAUNCHER_LDLIBS) #------------------------------------------------------------------------------ clean : $(RM) autorandr-launcher *.o 0707010000000B000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000004100000000autorandr-1.15.0.1709469470/contrib/autorandr_nitrogen_wallpaper0707010000000C000081ED00000000000000000000000165E46F1E00000CAF000000000000000000000000000000000000005E00000000autorandr-1.15.0.1709469470/contrib/autorandr_nitrogen_wallpaper/autorandr_nitrogen_wallpaper#!/usr/bin/env bash # autorandr_nitrogen_wallpaper # Copyright (c) 2015, Ondra 'Kepi' Kudlík, http://kepi.cz # # Simple script to switch wallpapers when autorandr change profile # # Usage # ===== # # 1. place this script (or better symlink it from autorandr location) # to ~/.config/autorandr/postswitch # 2. run "nitrogen" and set wallpapers for current profile as you wish # 3. run ~/.config/autorandr/postswitch savebg # 4. repeat steps 2-3 for any profile you wish # # License # ======= # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. NITROGEN_HOME="$HOME/.config/nitrogen" NITROGEN_BG="$NITROGEN_HOME/bg-saved.cfg" # try to detect profile PROFILE=$(autorandr 2>&1| grep detected |awk '{ print $1 }') [[ -n "$PROFILE" ]] || exit 1 PROFILE_BG_FILE="bg-saved.$PROFILE.cfg" PROFILE_BG="$NITROGEN_HOME/$PROFILE_BG_FILE" CP=$(which cp) MV=$(which mv) UNLINK=$(which unlink) NITROGEN=$(which nitrogen) # save background for detected profile if [[ $1 = 'savebg' ]]; then # nitrogen config doesn't exist, instruct to run it first if [[ ! -f "$NITROGEN_BG" ]]; then echo "wallpaper: you need to first run 'nitrogen' and set your wallpapers" exit 2 fi # nitrogen config exists but is broken symlink, just remove it and instruct to run it first if [ ! -e "$NITROGEN_BG" ] ; then $UNLINK "$NITROGEN_BG" echo "wallpaper: you need to first run 'nitrogen' and set your wallpapers (config was broken)" exit 3 fi $CP -L "$NITROGEN_BG" "$PROFILE_BG" # load background for detected profile else # we have some profile background config for this setup if [[ -f "$PROFILE_BG" ]]; then # nitrogen original file exists and not symlink if [[ -f "$NITROGEN_BG" ]] && [[ ! -L "$NITROGEN_BG" ]]; then echo "wallpaper: Backing up nitrogen saved bg to $NITROGEN_BG.backup" $MV "$NITROGEN_BG" "$NITROGEN_BG".backup fi # set symlink echo "wallpaper: Found saved wallpaper for profile $PROFILE - changing" ln -f -s "$PROFILE_BG_FILE" "$NITROGEN_BG" # call nitrogen $NITROGEN --restore else echo "wallpaper: No saved wallpaper found for profile $PROFILE" fi fi 0707010000000D000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000003400000000autorandr-1.15.0.1709469470/contrib/bash_completion0707010000000E000081A400000000000000000000000165E46F1E00000645000000000000000000000000000000000000003E00000000autorandr-1.15.0.1709469470/contrib/bash_completion/autorandr# autorandr/auto-disper completion by Maciej 'macieks' Sitarz <macieks@freesco.pl> # XDG additions and service dir filtering by Vladimir-csp _autorandr () { local cur prev opts lopts prfls AR_DIRS OIFS COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}" opts="-h -c -s -r -l -d" lopts="--help --change --cycle --save --remove --load --list --default --force --fingerprint --match-edid --config --dry-run" # find system-level autorandr dirs OIFS="$IFS" IFS=':' for DIR in ${XDG_CONFIG_DIRS:-/etc/xdg} do IFS="$OIFS" [ -d "$DIR/autorandr" ] && AR_DIRS=( "${AR_DIRS[@]}" "$DIR/autorandr" ) done IFS="$OIFS" # find user-level autorandr dir if [ -d "$HOME/.autorandr" ]; then AR_DIRS=( "${AR_DIRS[@]}" "$HOME/.autorandr" ) elif [ -d "${XDG_CONFIG_HOME:-$HOME/.config}/autorandr/" ]; then AR_DIRS=( "${AR_DIRS[@]}" "${XDG_CONFIG_HOME:-$HOME/.config}/autorandr/" ) fi if [ "${#AR_DIRS[@]}" -gt 0 ] then prfls="$(find "${AR_DIRS[@]}" -mindepth 1 -maxdepth 1 -type d ! -name "*.d" -printf '%f\n' 2>/dev/null | sort -u)" else prfls="" fi case "${cur}" in --*) COMPREPLY=( $( compgen -W "${lopts}" -- $cur ) ) return 0 ;; -*) COMPREPLY=( $( compgen -W "${opts} ${lopts}" -- $cur ) ) return 0 ;; *) if [ $COMP_CWORD -eq 1 ]; then COMPREPLY=( $( compgen -W "${opts} ${lopts}" -- $cur ) ) fi ;; esac case "${prev}" in -r|--remove|-l|--load|-d|--default) COMPREPLY=( $( compgen -W "${prfls}" -- $cur ) ) return 0 ;; *) ;; esac return 0 } complete -F _autorandr autorandr 0707010000000F000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000002800000000autorandr-1.15.0.1709469470/contrib/etc07070100000010000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000002C00000000autorandr-1.15.0.1709469470/contrib/etc/xdg07070100000011000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000003600000000autorandr-1.15.0.1709469470/contrib/etc/xdg/autostart07070100000012000081A400000000000000000000000165E46F1E000000D4000000000000000000000000000000000000005100000000autorandr-1.15.0.1709469470/contrib/etc/xdg/autostart/autorandr-launcher.desktop[Desktop Entry] Name=Autorandr Launcher Comment=Automatically run autorandr whenever the configuration changes Type=Application Exec=/usr/bin/autorandr-launcher --daemonize X-GNOME-Autostart-Phase=Initialization 07070100000013000081A400000000000000000000000165E46F1E00000148000000000000000000000000000000000000005500000000autorandr-1.15.0.1709469470/contrib/etc/xdg/autostart/autorandr-lid-listener.desktop[Desktop Entry] Name=Autorandr Lid Listener Comment=Trigger autorandr whenever the lid state changes Type=Application Exec=bash -c "stdbuf -oL libinput debug-events | egrep --line-buffered '^ event[0-9]+\s+SWITCH_TOGGLE\s' | while read line; do autorandr --change --default default; done" X-GNOME-Autostart-Phase=Initialization 07070100000014000081A400000000000000000000000165E46F1E000000D4000000000000000000000000000000000000004800000000autorandr-1.15.0.1709469470/contrib/etc/xdg/autostart/autorandr.desktop[Desktop Entry] Name=Autorandr Comment=Automatically select a display configuration based on connected devices Type=Application Exec=/usr/bin/autorandr -c --default default X-GNOME-Autostart-Phase=Initialization 07070100000015000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000003400000000autorandr-1.15.0.1709469470/contrib/fish_completion07070100000016000081A400000000000000000000000165E46F1E00000691000000000000000000000000000000000000004300000000autorandr-1.15.0.1709469470/contrib/fish_completion/autorandr.fish# don't complete directories and paths complete -c autorandr -f set -l virtual_profiles off common clone-largest horizontal vertical set -l user_profiles (autorandr --list) set -l profile_users -d --default -s --save -l --load -r --remove complete -c autorandr -n "__fish_seen_subcommand_from $profile_users" \ -a "$virtual_profiles $user_profiles" complete -c autorandr -s -h -l help -d 'get help' complete -c autorandr -s -c -l change -d 'automatically load the first detected profile' complete -c autorandr -s -d -l default -d 'set default PROFILE' complete -c autorandr -s -l -l load -d 'load PROFILE' complete -c autorandr -s -s -l save -d 'save current setup to a PROFILE' complete -c autorandr -s -r -l remove -d 'remove PROFILE' complete -c autorandr -l current -d 'list curren active configurations' complete -c autorandr -l cycle -d 'cycle through all detected drofiles' complete -c autorandr -l config -d 'dump current xrandr setup' complete -c autorandr -l debug -d 'enable verbose output' complete -c autorandr -l dry-run -d 'don\'t change anything' complete -c autorandr -l fingerprint -d 'fingerprint current hardware' complete -c autorandr -l match-edid -d 'match displays using edid' complete -c autorandr -l force -d 'force loading of a profile' complete -c autorandr -l list -d 'list all profiles' complete -c autorandr -l skip-options -d 'Set a comma-separated lis of xrandr arguments to skip buth in change detection and profile application' complete -c autorandr -l ignore-lid -d 'By default, closed lids are considered as disconnected if other outputs are detected. This flag disables this behavior' complete -c autorandr -l version -d 'show version' 07070100000017000081ED00000000000000000000000165E46F1E00000120000000000000000000000000000000000000003200000000autorandr-1.15.0.1709469470/contrib/listen_lid.sh#!/bin/sh # # /!\ You must be part of the input group # sudo gpasswd -a $USER input stdbuf -oL libinput debug-events | \ grep -E --line-buffered '^[[:space:]-]+event[0-9]+[[:space:]]+SWITCH_TOGGLE[[:space:]]' | \ while read line; do autorandr --change --default default done 07070100000018000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000002E00000000autorandr-1.15.0.1709469470/contrib/packaging07070100000019000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000003500000000autorandr-1.15.0.1709469470/contrib/packaging/debian0707010000001A000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000003C00000000autorandr-1.15.0.1709469470/contrib/packaging/debian/debian0707010000001B000081A400000000000000000000000165E46F1E00000241000000000000000000000000000000000000004400000000autorandr-1.15.0.1709469470/contrib/packaging/debian/debian/controlPackage: autorandr Version: 1.0 Section: x11 Priority: optional Maintainer: Phillip Berndt <phillip.berndt@googlemail.com> Build-Depends: debhelper (>=9) Standards-Version: 3.9.6 Homepage: https://github.com/phillipberndt/autorandr Architecture: all Depends: x11-xserver-utils, python3 Description: Automatically select a display configuration for connected devices Autorandr is a script for managing xrandr configurations based on the connected devices. It can be set up to automatically switch to a stored configuration whenever a change in the configuration is detected. 0707010000001C000081ED00000000000000000000000165E46F1E00000471000000000000000000000000000000000000004100000000autorandr-1.15.0.1709469470/contrib/packaging/debian/make_deb.sh#!/bin/sh # # Determine version if git rev-parse --git-dir >/dev/null 2>&1; then V="$(git describe --tags 2>/dev/null)" if [ "$?" -ne 0 ]; then V=0.1 fi else V=0.1 fi # Create/determine working directory P="`dirname $(readlink -f "$0")`" LD="autorandr-$V" D="$P/$LD" O="`pwd`/$LD.deb" if [ -d "$D" ]; then echo "Directory $D does already exist. Aborting.." exit 1 fi # Error handling: On error, abort and clear $D _cleanup() { rm -rf "$D" } trap _cleanup EXIT set -e mkdir $D # Debian(ish) specific part make -C "$P/../../../" \ DESTDIR="$D" \ TARGETS="autorandr bash_completion autostart_config systemd udev" \ BASH_COMPLETION_DIR=/usr/share/bash-completion/completions \ SYSTEMD_UNIT_DIR=/lib/systemd/system \ PM_UTILS_DIR=/usr/lib/pm-utils/sleep.d \ UDEV_RULES_DIR=/lib/udev/rules.d/ \ install SIZE=$(du -s $D | awk '{print $1}') cp -r "$P/debian" "$D/DEBIAN" chmod 0755 "$D/DEBIAN" [ -d "$D/etc" ] && (cd $D; find etc -type f -printf '/%p\n') > "$D/DEBIAN/conffiles" sed -i -re "s#Version:.+#Version: $V#" "$D/DEBIAN/control" echo "Installed-Size: $SIZE" >> "$D/DEBIAN/control" fakeroot dpkg-deb -b "$D" "$O" 0707010000001D000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000003200000000autorandr-1.15.0.1709469470/contrib/packaging/rpm0707010000001E000081A400000000000000000000000165E46F1E000009B7000000000000000000000000000000000000004100000000autorandr-1.15.0.1709469470/contrib/packaging/rpm/autorandr.specName: autorandr Version: 1.12.1 Release: %autorelease Summary: Automatically select a display configuration based on connected devices BuildArch: noarch BuildRequires: python3-devel License: GPLv3 URL: https://github.com/phillipberndt/%{name} Source0: %{url}/archive/%{version}/%{name}-%{version}.tar.gz BuildRequires: make BuildRequires: systemd BuildRequires: udev BuildRequires: desktop-file-utils Recommends: (%{name}-bash-completion = %{version}-%{release} if bash) Recommends: (%{name}-fish-completion = %{version}-%{release} if fish) Recommends: (%{name}-zsh-completion = %{version}-%{release} if zsh) %description %{summary}. %prep %setup -q %py3_shebang_fix ./autorandr.py %post udevadm control --reload-rules %systemd_post autorandr.service %preun %systemd_preun autorandr.service %postun %systemd_postun autorandr.service %package bash-completion Summary: Bash completion for autorandr Requires: %{name} Requires: bash-completion %description bash-completion This package provides bash-completion files for autorandr %package fish-completion Summary: Fish completion for autorandr Requires: %{name} Requires: fish-completion %description fish-completion This package provides fish-completion files for autorandr %package zsh-completion Summary: Zsh completion for autorandr Requires: zsh Requires: %{name} %description zsh-completion This package provides zsh-completion files for autorandr %install %make_install install -vDm 644 README.md -t "%{buildroot}/usr/share/doc/%{name}/" install -vDm 644 contrib/bash_completion/autorandr -t %{buildroot}%{_datadir}/bash-completion/completions/ install -vDm 644 contrib/fish_completion/autorandr.fish -t %{buildroot}%{_datadir}/fish/vendor_completions.d/ install -vDm 644 contrib/zsh_completion/_autorandr -t %{buildroot}%{_datadir}/zsh/site-functions/ install -vDm 644 autorandr.1 -t %{buildroot}%{_mandir}/man1/ %check desktop-file-validate %{buildroot}%{_sysconfdir}/xdg/autostart/autorandr.desktop %files %license gpl-3.0.txt %doc README.md %{_mandir}/man1/* %{_bindir}/autorandr %{_unitdir}/autorandr.service %{_sysconfdir}/xdg/autostart/autorandr.desktop %{_udevrulesdir}/40-monitor-hotplug.rules %files bash-completion %{_datadir}/bash-completion/completions/autorandr %files fish-completion %{_datadir}/fish/vendor_completions.d/autorandr.fish %files zsh-completion %{_datadir}/zsh/site-functions/_autorandr %changelog %autochangelog 0707010000001F000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000002D00000000autorandr-1.15.0.1709469470/contrib/pm-utils07070100000020000081ED00000000000000000000000165E46F1E000000A1000000000000000000000000000000000000003900000000autorandr-1.15.0.1709469470/contrib/pm-utils/40autorandr#!/bin/sh # # 40autorandr: Change autorandr profile on thaw/resume case "$1" in thaw|resume) /usr/bin/autorandr --batch --change --default default ;; esac 07070100000021000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000002C00000000autorandr-1.15.0.1709469470/contrib/systemd07070100000022000081A400000000000000000000000165E46F1E0000018C000000000000000000000000000000000000004B00000000autorandr-1.15.0.1709469470/contrib/systemd/autorandr-lid-listener.service[Unit] Description=Runs autorandr whenever the lid state changes [Service] Type=simple ExecStart=sh -c "stdbuf -oL libinput debug-events | grep -E --line-buffered '^[[:space:]-]+event[0-9]+[[:space:]]+SWITCH_TOGGLE[[:space:]]' | while read line; do autorandr --batch --change --default default; done" Restart=always RestartSec=30 SyslogIdentifier=autorandr [Install] WantedBy=multi-user.target 07070100000023000081A400000000000000000000000165E46F1E00000109000000000000000000000000000000000000003E00000000autorandr-1.15.0.1709469470/contrib/systemd/autorandr.service[Unit] Description=autorandr execution hook After=sleep.target StartLimitIntervalSec=5 StartLimitBurst=1 [Service] ExecStart=/usr/bin/autorandr --batch --change --default default Type=oneshot RemainAfterExit=false KillMode=process [Install] WantedBy=sleep.target 07070100000024000041ED00000000000000000000000265E46F1E00000000000000000000000000000000000000000000003300000000autorandr-1.15.0.1709469470/contrib/zsh_completion07070100000025000081A400000000000000000000000165E46F1E00000758000000000000000000000000000000000000003E00000000autorandr-1.15.0.1709469470/contrib/zsh_completion/_autorandr#compdef autorandr __autorandr_profile () { declare -a virtual virtual=("off":"disable all outputs" "common":"clone at the largest common resolution" "clone-largest":"clone with the largest resolution" "horizontal":"stack all connected outputs horizontally" "vertical":"stack all connected outputs vertically") _describe -t virtual-profiles "virtual profiles" virtual __autorandr_saved_profile } __autorandr_saved_profile () { declare -a saved saved=(${${(f)${:-"$(autorandr)"}}/ /:}) _describe -t profiles "saved profiles" saved } _autorandr () { local curcontext="$curcontext" state line exclude="-s --save -l --load -r --remove -c --change" _arguments -C \ "(: -)"{-h,--help}"[get help]" \ "($exclude)"{-c,--change}"[automatically load the first detected profile]" \ "($exclude)"{-d,--default}"[set default profile]:profile:__autorandr_profile" \ "($exclude)"{-l,--load}"[load profile]:profile:__autorandr_profile" \ "($exclude)"{-s,--save}"[save current setup to a profile]:profile: " \ "($exclude)"{-r,--remove}"[remove profile]:profile:__autorandr_saved_profile" \ --batch"[run autorandr for all users]" \ --current"[list current active configurations]" \ --cycle"[cycle through all detected profiles]" \ --config"[dump current xrandr setup]" \ --debug"[enable verbose output]" \ --dry-run"[don't change anything]" \ --fingerprint"[fingerprint current hardware]" \ --match-edid"[match displays using edid]" \ --force"[force loading of a profile]" \ --list"[list all profiles]" \ --skip-options"[skip xrandr options]:xrandr options:_values -s , options gamma brightness panning transform primary mode pos rate" \ --version"[show version]" } _autorandr "$@" 07070100000026000081A400000000000000000000000165E46F1E0000894B000000000000000000000000000000000000002800000000autorandr-1.15.0.1709469470/gpl-3.0.txt GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. 07070100000027000081A400000000000000000000000165E46F1E000005E7000000000000000000000000000000000000002500000000autorandr-1.15.0.1709469470/setup.pyfrom setuptools import setup try: long_description = open('README.md').read() except: long_description = 'Automatically select a display configuration based on connected devices' setup( name='autorandr', version='1.15.post1', description='Automatically select a display configuration based on connected devices', long_description=long_description, long_description_content_type="text/markdown", url='https://github.com/phillipberndt/autorandr', author='Phillip Berndt', author_email='phillip.berndt@googlemail.com', license='GPLv3', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', ], keywords='xrandr', py_modules=['autorandr'], entry_points={ 'console_scripts': [ 'autorandr = autorandr:exception_handled_main', ], }, ) 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!326 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor