Wayland环境(sway)截屏

wayland显示服务器协议sway - i3兼容Wayland compositor 桌面,我需要做一些截图以便撰写文档:

  • 通过 sway 的快捷键执行脚本,完成屏幕截图

  • 简单的截图标记(文字和线框等)

参考 Taking Screenshots on Wayland 略作修改(主要是我 MacBook Air上运行Arch Linux ,而 MacBook Air 11" Late 2010 没有 print 按键):

安装截屏需要的软件包
pacman -S jq grim slurp swappy
  • 创建 ~/bin/screenshot.sh 脚本(注意需要通过 chmod +x ~/bin/acreenshot.sh 设置可执行属性):

创建 ~/bin/screenshot.sh 脚本
#!/usr/bin/env sh
# Take a screenshot on wayland with swaymsg, jq, grim, slurp, and swappy
#
# Make sure the script is executable (chmod +x ./screenshot.sh)
#
# If you don't use sway, replace `swaymsg` with whatever your window manager
# gives you to query window information.
#
# Example sway configuration
#
# bindsym Print             exec ~/.local/bin/screenshot.sh region
# bindsym Shift+Print       exec ~/.local/bin/screenshot.sh window
# bindsym Ctrl+Print        exec ~/.local/bin/screenshot.sh output
# bindsym Ctrl+Shift+Print  exec ~/.local/bin/screenshot.sh all


# region|window|output|all
mode="$1"

case $mode in
    "region")
        grim -g "$(slurp)" - | swappy -f -
        ;;
    "window")
        grim -g "$(swaymsg -t get_tree | jq -j '.. | select(.type?) | select(.focused).rect | "\(.x),\(.y) \(.width)x\(.height)"')" - | swappy -f -
        ;;
    "output")
        grim -o $(swaymsg -t get_outputs | jq -r '.[] | select(.focused) | .name') - | swappy -f -
        ;;
    "all")
        grim - | swappy -f -
        ;;
    *)
        echo >&2 "unsupported command \"$mode\""
        echo >&2 "Usage:"
        echo >&2 "screenshot.sh <region|window|output|all>"
        exit 1
esac
  • 配置 ~/.config/sway/config (只做了一点点修改以适应我的使用,你也可以自己定义不同的快捷键) :

配置 ~/.config/sway/config
# ScreenShot
bindsym $mod+z             exec ~/bin/screenshot.sh region
bindsym Shift+$mod+z       exec ~/bin/screenshot.sh window
bindsym Ctrl+$mod+z        exec ~/bin/screenshot.sh output
bindsym Ctrl+Shift+$mod+z  exec ~/bin/screenshot.sh all

注意,我这里用 $mod+z 代理 PRINT 键。使用 ctrl+$mod+c 组合键重新加载 sway - i3兼容Wayland compositor 配置就可以开始使用截屏功能

../../../_images/sway_screen_shot_region.png

使用 $mod+z 对屏幕区域进行截屏,效果

此外,最终处理程序 swaypy 还提供了简单的图片标注功能

脚本解释

使用到3个程序的pipeline:

组合了3个程序实现屏幕区域截图
grim -g "$(slurp)" - | swappy -f -
  • 首先是 grim 会通过 -g 参数表示从 region (区域)截屏( region 值是 slurp 提供的)

  • 接下来 slurp 程序会获得 从 (x,y) 开始到 (<width>x<height>) 的座标,这个座标会被 grim 程序读取(即 -g 获得的区域范围)以便截图

  • 通过管道 | 将截取的图片传输给 swaypy (交互的简单图片处理程序)处理

  • 此外的截取窗口或输出则是由 sway - i3兼容Wayland compositor 平台的 swaymsg 实现

参考