最近想折腾 Xfce,而且 Fedora 的包都好老啊,所以换了 Arch Linux… 果然装完就有的折腾了:Xfce 4.0 居然不支持双显示器扩展桌面(extended desktop)!如果通过调用 xrandr 动态增加显示器的方法,在拔出显示器的时候居然笔记本内置的显示器分辨率设置会乱掉…
针对不能自动检测、自动调整的问题,我发现了其实可以用 inotify 检测 /sys/class/drm/card0-VGA-1/status
这个文件的改动(其实做不到,继续读),然后在有改动的时候调用 xrandr 来配置/关闭外接显示器。
首先俺在 Terminal 里面运行:
[jiehan@tpx300 ~]$ cat /sys/class/drm/card0-VGA-1/status connected
然后在拔出 VGA1 上的显示器后,再运行能显示:
[jiehan@tpx300 ~]$ cat /sys/class/drm/card0-VGA-1/status disconnected
既然如此,inotifywait -e modify /sys/class/drm/card0-VGA-1/status
就能在/sys/class/drm/card0-VGA-1/status
被改动的时候返回了吧?
—— 可是… 事实不是这样的(废话,要是这样的话还折腾啥呢?为啥呢,因为 inotify FAQ 里有这句话:
Q: Can I watch sysfs (procfs, nfs…)?
Simply spoken: yes, but with some limitations. These limitations vary between kernel versions and tend to get smaller. Please read information about particular filesystems.
诶,那看看总共能用啥吧… 来监视一下所有的事件,如下是运行后插拔显示器 stdout 的输出:
[jiehan@tpx300 ~]$ inotifywait -m /sys/class/drm/card0-VGA-1/status 2> /dev/null /sys/class/drm/card0-VGA-1/status OPEN /sys/class/drm/card0-VGA-1/status ACCESS /sys/class/drm/card0-VGA-1/status CLOSE_NOWRITE,CLOSE /sys/class/drm/card0-VGA-1/status OPEN /sys/class/drm/card0-VGA-1/status ACCESS /sys/class/drm/card0-VGA-1/status CLOSE_NOWRITE,CLOSE ^C
啥?OPEN、ACCESS、CLOSE_NOWRITE 和 CLOSE 事件?为啥实际 MODIFY 了但是没事件呢?估计是因为 /sys
是个 sysfs 吧,鬼知道… 所以我们只能 inotifywait 任何一个关于/sys/class/drm/card0-VGA-1/status
的事件了。这也就要求你没事不要老去读那个文件,不然每次你的脚本都得判断一下…
好吧,那就酱紫:
[jiehan@tpx300 ~]$ cat bin/dual-monitor-watch #!/bin/bash function connection_check { if [ "connected" = $( cat /sys/class/drm/card0-VGA-1/status ) ]; then setup_monitorelse turn_off_monitorfi } function setup_monitor { notify-send 'Secondary monitor detected' 'xrandr --output VGA1 --auto --right-of LVDS1' --icon=dialog-information xrandr --output VGA1 --auto --right-of LVDS1 } function turn_off_monitor { notify-send 'Secondary monitor disconnected' 'xrandr --output VGA1 --off' --icon=dialog-information xrandr --output VGA1 --off } notify-send 'Ready to handle secondary monitor' --icon=dialog-information connection_check while inotifywait /sys/class/drm/card0-VGA-1/status &> /dev/null; do connection_checkdone done
然后可以把 /home/$USER/bin/dual-monitor-watch
给 chmod +x
了然后给放到 Session and Startup 里面自动启动就好啦~
说明:
inotifywait 在 inotify-tools 包中,使用前得先安装。
VGA1
这样的标识可以通过 xrandr -q
得到。
限制:
这个脚本没做锁,所以进入桌面那次运行就行了别反复运行…
这个脚本确实有问题,比如如果你先拔了显示器在 xrandr 还没运行完的时候就又给显示器插上了,那 inotifywait 还没来及运行呢… 懒得改了,自重吧… 反正是你自己电脑 :D
参考链接:
https://jiehan.org/tech/xfce-dual-monitor-with-hotplugging-capabilities/
个人阅后感想:
我靠,真的不一般,好吧,我承认我收获了很多东西。
很值得学习的。。。
PS. 一些备注
xrandr 命令行可以很方便地切换双屏,常用方式如下,其他的可以自己探索: