Featured image of post CachyOS与niri常用配置

CachyOS与niri常用配置

记录我将主力系统迁移到CachyOS+niri环境下踩的坑与解决方案

前言

在23年的时候,我就将我的电脑装上Arch Linux体验了一把Linux桌面,当时使用的是KDE作为桌面环境。KDE作为经典的桌面环境确实非常稳定与好用,但操作逻辑和Windows差不多,并没有什么特别的地方,再加上当时在Linux下打游戏很不方便,所以用了一阵还是切回了Windows。到了25年又手痒想折腾了,把Arch重新装了回来,顺手写了篇安装教程,不过也没坚持多久,最后还是回到了Windows。

仔细想想,前两次放弃Linux的原因主要是下面这三点:

  1. 对游戏支持太差
  2. NVIDIA显卡在Linux下存在很多影响体验的BUG
  3. 总有许多零碎的小问题要自己排查

不过放到现在,这些问题基本都有了眉目。V社持续发力的Proton已经能跑起大部分游戏;NVIDIA也开源了内核模块,Linux下的驱动体验在一步步变好;最重要的还是AI大人的发展,遇到系统里的各种小毛病,直接丢给Agent就能帮你排查修好,不用像以前那样古法搜索翻半天Wiki和论坛了。

另外,这次下定决心离开Windows也有几个很直接的原因。平时在Windows下写代码本来就都是在WSL里跑,之前用Codex在PowerShell下折腾得很难受,与其隔着一层,不如直接上原生Linux。游戏方面,现在不玩三角洲了,平时还会打开的游戏在Linux上都能正常运行。还有一个推力是之前体验过macOS多工作区平滑切换的感觉,非常顺手,Windows上一直找不到类似的体验,所以这次打算顺便试试平铺式窗口管理器。

平铺式这块,一开始想用的是Hyprland,界面好看用的人也多,但我不太喜欢它每次新开窗口都会把已有窗口挤小的设计。刷论坛时看到有人推荐niri,这种横向无限滚动的布局正好和我想要的效果一致,就定下来用niri了。

系统上看到不少人推荐CachyOS,它在原版Arch的基础上做了不少内核和游戏优化,驱动安装也简化了很多,而且自带一套现成的niri配置,不用从零开始手搓,开箱就能用,所以最终选择了这个发行版。

系统安装

安装部分比较简单,CachyOS自带图形化安装器,一路按提示选好分区和桌面环境下一步就行。如果对btrfs分区、快照这些概念不熟,可以参考我之前那篇Arch安装文章里的说明。不过在安装确认的summary界面,最好去手动的修改一下镜像源。虽然安装程序会自动调用rate-mirrors测速,但是其选择的不如自己指定的速度快。

我们在终端中执行下面的操作:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 配置 CachyOS 国内镜像(以中科大为例)
echo 'Server = https://mirrors.ustc.edu.cn/cachyos/repo/$arch/$repo' | sudo tee /etc/pacman.d/cachyos-mirrorlist
echo 'Server = https://mirrors.ustc.edu.cn/cachyos/repo/$arch_v3/$repo' | sudo tee /etc/pacman.d/cachyos-v3-mirrorlist
echo 'Server = https://mirrors.ustc.edu.cn/cachyos/repo/$arch_v4/$repo' | sudo tee /etc/pacman.d/cachyos-v4-mirrorlist

# 同时配置 Arch Linux 国内镜像
echo 'Server = https://mirrors.ustc.edu.cn/archlinux/$repo/os/$arch' | sudo tee /etc/pacman.d/mirrorlist

# 注释掉自动更新镜像的脚本
sudo vim /etc/calamares/scripts/update-mirrorlist

装完进系统后,我们之前更换的软件源还存在,所以只需要禁用cachyos-rate-mirrors避免其自动更换我们的镜像即可。这里我直接选择卸载:

1
sudo pacman -R cachyos-rate-mirrors

接着启用archlinuxcn软件源,方便后面装一些国内常用的包。在/etc/pacman.conf末尾加上两行:

1
2
[archlinuxcn]
Server = https://mirrors.ustc.edu.cn/archlinuxcn/$arch

最后更新一下软件包索引并安装密钥环:

1
2
sudo pacman -Syyu
sudo pacman -S archlinuxcn-keyring

环境优化

换完源之后,就可以开始装输入法、常用软件、配字体以及挂载原来的Windows分区了。这些基础项大部分在之前的文章里都写过,这里只列一下关键步骤和niri环境下多出来的配置。

安装输入法

输入法继续沿用我一直在用的fcitx5 + rime方案,搭配雾凇拼音词库和小鹤双拼。词库配置和多端同步的具体步骤可以看之前的Arch安装文章以及rime多端同步文章,这里就不再重复贴配置文件了。

安装所需的包:

1
sudo pacman -S fcitx5-im fcitx5-rime rime-ice-git

和KDE里直接在设置界面勾选虚拟键盘不同,niri下需要自己配置自启和环境变量。在niri的配置中(如~/.config/niri/config.kdl或拆分出来的autostart.kdl、misc.kdl)加入以下内容:

1
2
3
4
5
6
7
8
spawn-at-startup "fcitx5" "-d"

environment {
    ELECTRON_OZONE_PLATFORM_HINT "auto"
    QT_IM_MODULES "wayland;fcitx"
    QT_IM_MODULE "fcitx"
    XMODIFIERS "@im=fcitx"
}

Wayland下一般不建议在全局环境变量里直接设GTK_IM_MODULE(否则fcitx5会弹警告),对于GTK程序,直接编辑~/.config/gtk-3.0/settings.ini(GTK4同理,改~/.config/gtk-4.0/settings.ini)指定输入法模块就行:

1
2
[Settings]
gtk-im-module = fcitx

至于Qt和XWayland程序,靠前面environment里的几个变量兜底即可;加上ELECTRON_OZONE_PLATFORM_HINT "auto"则能让大多数Electron应用默认走Wayland,避免输入法候选框错位或者打不出中文。

安装常用软件

CachyOS默认自带了paru,安装AUR里的软件很省事。niri本身只是个窗口管理器,没有附带文本编辑器、看图和归档管理器这类基础工具,我直接借用了GNOME全家桶里的几个轻量应用,界面干净而且对Wayland适配得不错。

1
2
3
4
5
6
7
8
# WPS
paru -S wps-office-cn ttf-wps-fonts wps-office-mui-zh-cn

# GNOME环境下常用软件(文本编辑、照片查看、压缩包查看)
sudo pacman -S gnome-text-editor loupe file-roller

# VSCode
paru -S visual-studio-code-bin

配置默认字体

Linux默认的中文字体显示还是有不少老毛病(异体字、全角引号等),具体的原理和完整的fonts.conf都在之前的fontconfig配置文章和Arch安装文章里写过,这里直接装好字体再把配置复制过去就行。

1
2
sudo pacman -S ttc-iosevka ttf-nerd-fonts-symbols
paru -S ttf-twemoji ttf-lxgw-wenkai 

把~/.config/fontconfig/fonts.conf放好后就能生效。

另外,平时用WPS时,经常会用到Windows自带的微软雅黑、宋体、黑体、Times New Roman这些字体。等下面把Windows分区挂载好之后,直接把常用的几个字体从/mnt/win11/Windows/Fonts复制到~/.local/share/fonts就行:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
mkdir -p ~/.local/share/fonts
cd /mnt/win11/Windows/Fonts

# 等线、微软雅黑
cp Deng.ttf Dengb.ttf Dengl.ttf msyh.ttc msyhbd.ttc msyhl.ttc ~/.local/share/fonts/
# 仿宋、黑体、楷体、宋体
cp simfang.ttf simhei.ttf simkai.ttf simsun.ttc simsunb.ttf SimsunExtG.ttf ~/.local/share/fonts/
# Times New Roman
cp times.ttf timesbd.ttf timesbi.ttf timesi.ttf ~/.local/share/fonts/

# 刷新字体缓存
fc-cache -fv

挂载Windows分区

以前在Linux下挂载NTFS分区,要么用用户态的ntfs-3g,要么用Paragon的内核驱动ntfs3。从Linux 7.1内核开始,主线正式合入了全新的NTFS读写驱动,基于现代内核接口重写,性能和维护情况都比之前好了不少。CachyOS跟进内核非常快,直接用这个新驱动来挂载原来的Windows分区就行。

先查看一下NTFS分区的UUID,并把本地挂载目录建好:

1
2
3
4
5
# 查看分区 UUID 和文件系统类型
lsblk -f

# 创建挂载目录
sudo mkdir -p /mnt/win11 /mnt/data

接着编辑/etc/fstab,在末尾加上对应的挂载项(把下面的UUID换成上面lsblk -f查到的实际值):

1
2
UUID=你的Win11分区UUID  /mnt/win11  ntfs  iocharset=utf8,umask=0,windows_names  0  0
UUID=你的数据分区UUID   /mnt/data   ntfs  iocharset=utf8,umask=0,windows_names  0  0

这里用到的几个挂载参数:

  • iocharset=utf8:正常显示中文文件名,避免乱码
  • umask=0:放开读写权限,方便普通用户直接操作(如果想限制为仅当前用户可读写,也可以换成uid=1000,gid=1000)
  • windows_names:禁止写入Windows不支持的非法文件名,免得以后切回Windows打不开

写完后先别急着重启,先刷新一下配置并测试挂载,没报错就说明没问题了:

1
2
sudo systemctl daemon-reload
sudo mount -a
💡 提示

双系统环境下记得在Windows的电源设置里关掉「快速启动」,不然Windows关机时其实处于休眠状态,分区会被锁住,在Linux下可能会挂载失败或变成只读。

设置时间同步

Linux和Windows双系统切换时经常会遇到时间差8小时的问题,原因是Linux默认把主板硬件时钟当作UTC时间,而Windows默认当作本地时间。比较省事的做法是让Windows这边也统一改用UTC,在Windows里以管理员身份打开终端执行下面这条命令即可:

1
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation" /v RealTimeIsUniversal /d 1 /t REG_DWORD /f

改完后重启,两个系统的时间就能对上了。

Nvidia

虽然现在NVIDIA对Linux的支持已经比之前好很多了,而且还推出了开源驱动,但在niri环境下依然存在几个比较影响体验的问题。

高刷新率下屏幕渲染闪烁

用DP线接高刷显示器的时候,由于带宽限制会触发DSC,在niri下就容易出现屏幕渲染闪烁的问题。在KDE环境下可以通过设置颜色准确率优先来规避,但在niri里这还是个悬而未决的问题,对应的issue1已经挂了一年多还没解决。

由于根因在上游驱动,niri官方并不打算为此做专门的妥协,好在社区大佬已经在Smithay那边提了一个缓解方案的PR2,只是还没合并进主线。这个PR会把上一帧的scanout缓冲区多保留一帧,借此避免闪烁,不过选项默认是关闭的,所以除了给Smithay打补丁,还得在niri里加一行代码把它打开。

既然主线还没合,那就只能自己编译了。让AI手搓了一个打包脚本,把下面的PKGBUILD和niri-enable-pr2151.patch放到同一个目录下,直接执行makepkg -si就能用上修复版本的niri。

niri-enable-pr2151.patch:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
diff --git a/src/backend/tty.rs b/src/backend/tty.rs
--- a/src/backend/tty.rs
+++ b/src/backend/tty.rs
@@ -1512,6 +1512,10 @@
             }
         };
 
+        // Smithay PR #2151: delay reusing the previous scanout buffer by one frame.
+        // The Smithay option defaults to false, so explicitly enable it here.
+        compositor.set_keep_previous_frame_buffer(true);
+
         if self.debug_tint {
             compositor.set_debug_flags(DebugFlags::TINT);
         }

PKGBUILD:

📃展开 PKGBUILD
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# Based on the AUR niri-spicy-git and niri-git PKGBUILDs.
# Original contributors: Christopher Snowhill, cosmo, FreeFull,
# Julius Michaelis, and Nebulosa.

# Optional: env _sccache=y makepkg -si
: "${_sccache:=}"

pkgname=niri-smithay-pr2151-git
pkgver=26.04.r289.g541d138
pkgrel=1
pkgdesc='Scrollable-tiling Wayland compositor with Smithay PR #2151 enabled'
arch=(x86_64 aarch64)
url='https://github.com/niri-wm/niri'
license=(GPL-3.0-or-later)
depends=(cairo glib2 libdisplay-info libinput libpipewire libxkbcommon mesa pango pixman seatd)
makedepends=(clang cmake git pkgconf python rust)
if [[ -n "${_sccache}" ]]; then
  makedepends+=(sccache)
fi
optdepends=('fuzzel: application launcher'
            'waybar: Wayland bar'
            'alacritty: terminal emulator'
            'mako: notification daemon'
            'swaybg: wallpaper tool'
            'swaylock: screen locker'
            'xdg-desktop-portal-gtk: basic desktop portals'
            'xdg-desktop-portal-gnome: screencasting support'
            'gnome-keyring: secret portal'
            'polkit-gnome: authentication agent')
provides=("niri=${pkgver}" wayland-compositor)
conflicts=(niri niri-git niri-bin niri-spicy-git)
options=(!debug !lto !strip)

# Pin the PR patch, not its moving branch. Apply it to the Smithay revision
# required by upstream niri, so newer niri does not inherit an older Smithay API.
_smithay_pr_commit=0c649d2d6824b60b7bfe27f1fdb5f2fbf4311ac4
source=('niri::git+https://github.com/niri-wm/niri.git#branch=main'
        'smithay::git+https://github.com/Smithay/smithay.git'
        "smithay-pr2151.patch::https://github.com/Smithay/smithay/commit/${_smithay_pr_commit}.patch"
        'niri-enable-pr2151.patch')
b2sums=('SKIP'
        'SKIP'
        'd35585df83f397ecadcf3868bde945ed2a1da21a91dd9a57d7291649e71edb075d0a436ea8cea93925f88fd579049de6c8f28de24292ed690434c4dfe3be421e'
        '7d31e08206716eb216fe7a9e46f711ef769019f476b473fab18cef1b796556c587d483932730c37bb9537f4da4398dfdeb90d61b81ac5c983100667830d1e36f')

pkgver() {
  cd "${srcdir}/niri"
  git describe --long --tags --abbrev=7 | sed 's/\([^-]*-g\)/r\1/;s/-/./g;s/^v//'
}

# Both dependency fetching and compilation must use the same local overrides.
_cargo() {
  cargo --config "${srcdir}/smithay-patch.toml" "$@"
}

prepare() {
  local smithay_rev
  smithay_rev=$(python - "${srcdir}" <<'PY'
import json
import pathlib
import sys
import tomllib

src = pathlib.Path(sys.argv[1])
manifest = tomllib.loads((src / "niri/Cargo.toml").read_text())
deps = manifest["workspace"]["dependencies"]
names = ("smithay", "smithay-drm-extras")
upstream = "https://github.com/Smithay/smithay.git"
revisions = {deps[name]["rev"] for name in names}
if len(revisions) != 1 or any(deps[name]["git"] != upstream for name in names):
    sys.exit("Upstream changed its Smithay dependencies; review this PKGBUILD.")

# Patch BOTH crates so cargo cannot build two incompatible copies of Smithay.
lines = [f'[patch."{upstream}"]']
for name, path in (("smithay", src / "smithay"),
                   ("smithay-drm-extras", src / "smithay/smithay-drm-extras")):
    lines.append(f'{name} = {{ path = {json.dumps(str(path), ensure_ascii=False)} }}')
(src / "smithay-patch.toml").write_text("\n".join(lines) + "\n")
print(revisions.pop())
PY
  ) || return 1

  # makepkg's VCS checkout contains the upstream history. Reset only this
  # build checkout, which may still contain our patch from a previous prepare().
  git -C "${srcdir}/smithay" checkout --force --detach "${smithay_rev}" || return 1
  git -C "${srcdir}/smithay" apply --check "${srcdir}/smithay-pr2151.patch" || return 1
  git -C "${srcdir}/smithay" apply "${srcdir}/smithay-pr2151.patch" || return 1

  cd "${srcdir}/niri"
  # Allow prepare() to run again without double-patching.
  if ! git apply --reverse --check "${srcdir}/niri-enable-pr2151.patch" 2>/dev/null; then
    git apply --check "${srcdir}/niri-enable-pr2151.patch" || return 1
    git apply "${srcdir}/niri-enable-pr2151.patch" || return 1
  fi

  export CARGO_HOME="${srcdir}/cargo-home"
  # The original lockfile points to git dependencies. Allow cargo to update it
  # once for the local patched crates; build() is strictly frozen afterwards.
  _cargo fetch --target "$(rustc -vV | sed -n 's/^host: //p')"
}

build() {
  cd "${srcdir}/niri"
  export CARGO_HOME="${srcdir}/cargo-home"
  export CARGO_TARGET_DIR="${srcdir}/niri/target"
  export CARGO_ENCODED_RUSTFLAGS="--remap-path-prefix=${srcdir}=/"
  if [[ -n "${_sccache}" ]]; then
    export RUSTC_WRAPPER=sccache
  fi
  _cargo build --frozen --release --package niri
}

package() {
  cd "${srcdir}/niri"
  install -Dm755 target/release/niri -t "${pkgdir}/usr/bin/"
  install -Dm755 resources/niri-session -t "${pkgdir}/usr/bin/"
  install -Dm644 resources/default-config.kdl -t "${pkgdir}/usr/share/doc/niri/"
  install -Dm644 resources/niri.desktop -t "${pkgdir}/usr/share/wayland-sessions/"
  install -Dm644 resources/niri-portals.conf -t "${pkgdir}/usr/share/xdg-desktop-portal/"
  install -Dm644 resources/niri.service resources/niri-shutdown.target \
    -t "${pkgdir}/usr/lib/systemd/user/"
}
💡 提示

安装时会替换原有的niri包,装完之后记得退出当前niri会话重新登录,新编译的进程才会生效。

视频硬件解码

由于NVIDIA默认不支持VA-API,所以需要先装一个兼容层3把NVDEC桥接过去,再给浏览器配上对应的环境变量和参数。

1
sudo pacman -S libva-nvidia-driver

为了不让环境变量污染全局,Firefox这边我还是采用修改本地.desktop文件的方式来实现(具体复制和修改方法见后文「修改桌面程序启动变量」)。

Firefox

在.desktop文件的Exec前加上下面这些环境变量:

1
env MOZ_DISABLE_RDD_SANDBOX=1 LIBVA_DRIVER_NAME=nvidia CUDA_DISABLE_PERF_BOOST=1

然后在Firefox地址栏打开about:config,把下面几项都设为true:

  • media.ffmpeg.vaapi.enabled
  • media.hardware-video-decoding.force-enabled
  • media.rdd-ffmpeg.enabled
  • gfx.x11-egl.force-enabled

Edge

如果也用Edge,可以在~/.config/microsoft-edge-stable-flags.conf里加上下面的启动参数开启NVIDIA硬解:

1
2
3
--enable-features=AcceleratedVideoDecodeLinuxGL,VaapiOnNvidiaGPUs
--ignore-gpu-blocklist
--use-gl=angle --use-angle=gl

Niri配置

Bitwarden弹窗自动浮动

在平铺式桌面下,浏览器扩展弹出的Bitwarden小窗默认会被当成普通窗口直接平铺放大,填个密码占满半个屏幕非常别扭,需要单独配成浮动窗口。

Edge

Edge下的扩展弹窗有固定的app-id,直接在niri的window-rule里写一条规则就行:

1
2
3
4
5
6
7
// Bitwarden on msedge
window-rule {
  match app-id="msedge-jbkfoedolllekgbhcbcoahefnbanhhlh-Default"
  open-floating true
  default-floating-position x=10 y=30 relative-to="top-left"
  default-window-height { proportion 0.5; }
}

Firefox

Firefox这边稍微麻烦点,弹窗刚创建时还没有正确的标题,静态的window-rule匹配不到。官方FAQ4里也提到了这个问题,解决方法是跑一个Python脚本监听niri的事件流,等窗口标题更新成Bitwarden后再动态把它切成浮动并调好大小和位置。

创建脚本~/.config/niri/float.py:

📃展开代码
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/python3
"""
Like open-float, but dynamically. Floats a window when it matches the rules.

Some windows don't have the right title and app-id when they open, and only set
them afterward. This script is like open-float for those windows.

Usage: fill in the RULES array below, then run the script.
"""

from dataclasses import dataclass, field
import json
import os
import re
from socket import AF_UNIX, SHUT_WR, socket

@dataclass(kw_only=True)
class Match:
    title: str | None = None
    app_id: str | None = None

    def matches(self, window):
        if self.title is None and self.app_id is None:
            return False

        matched = True

        if self.title is not None:
            matched &= re.search(self.title, window["title"]) is not None
        if self.app_id is not None:
            matched &= re.search(self.app_id, window["app_id"]) is not None

        return matched

@dataclass
class Rule:
    match: list[Match] = field(default_factory=list)
    exclude: list[Match] = field(default_factory=list)

    def matches(self, window):
        if len(self.match) > 0 and not any(m.matches(window) for m in self.match):
            return False
        if any(m.matches(window) for m in self.exclude):
            return False

        return True

# Write your rules here. One Rule() = one window-rule {}.
RULES = [
    # window-rule {} with one match.
    Rule([Match(title="Bitwarden", app_id="firefox")]),

    # window-rule {} with one match and one exclude.
    # Rule(
    #     [Match(title="rs")],
    #     exclude=[Match(app_id="Alacritty")],
    # ),

    # window-rule {} with two matches.
    # Rule(
    #     [
    #         Match(app_id="^foot$"),
    #         Match(app_id="^mpv$"),
    #     ]
    # ),
]

if len(RULES) == 0:
    print("fill in the RULES list, then run the script")
    exit()

niri_socket = socket(AF_UNIX)
niri_socket.connect(os.environ["NIRI_SOCKET"])
file = niri_socket.makefile("rw")

_ = file.write('"EventStream"')
file.flush()
niri_socket.shutdown(SHUT_WR)

windows = {}

def send(request):
    with socket(AF_UNIX) as niri_socket:
        niri_socket.connect(os.environ["NIRI_SOCKET"])
        file = niri_socket.makefile("rw")
        _ = file.write(json.dumps(request))
        file.flush()

def float(id: int):
    send({"Action": {"MoveWindowToFloating": {"id": id}}})
    send({"Action": {"SetWindowWidth": {"id": id, "change": {"SetFixed": 450}}}})
    send({"Action": {"SetWindowHeight": {"id": id, "change": {"SetFixed": 670}}}})
    send({"Action": {
            "MoveFloatingWindow": {
                "id": id,
                "x": {"SetFixed": 1000.0},
                "y": {"SetFixed": 100.0}
            }
        }
    })

def update_matched(win):
    win["matched"] = False
    if existing := windows.get(win["id"]):
        win["matched"] = existing["matched"]

    matched_before = win["matched"]
    win["matched"] = any(r.matches(win) for r in RULES)
    if win["matched"] and not matched_before:
        print(f"floating title={win['title']}, app_id={win['app_id']}")
        float(win["id"])

for line in file:
    event = json.loads(line)

    if changed := event.get("WindowsChanged"):
        for win in changed["windows"]:
            update_matched(win)
        windows = {win["id"]: win for win in changed["windows"]}
    elif changed := event.get("WindowOpenedOrChanged"):
        win = changed["window"]
        update_matched(win)
        windows[win["id"]] = win
    elif changed := event.get("WindowClosed"):
        del windows[changed["id"]]

然后在niri配置里设置开机自启(路径里的用户名记得换成自己的):

1
spawn-at-startup "python3" "/home/luobo/.config/niri/float.py"

Edge原生鼠标手势窗口悬浮

在Linux下用Edge自带的鼠标手势,触发方式和Windows略有不同,需要先右键再按左键,或者双击右键拖动。不过在niri里触发手势时,它用来绘制轨迹的覆盖窗口同样会被当成普通窗口平铺出来。

因为这个手势窗口没有app-id和title,所以在niri的规则里直接匹配空值并设为浮动即可修复:

1
2
3
4
window-rule {
    match app-id="^$" title="^$"
    open-floating true
}

X11托盘图标修复

使用Wine或者一些老旧的X11应用时,经常会遇到它们单独弹出一个小方块显示托盘图标,而不是正常进到状态栏的系统托盘区里。这是因为它们还在用老的XEmbed协议,而Wayland下的状态栏用的是SNI(StatusNotifierItem)协议,需要一个桥接程序来做转换。

在KDE环境下有自带的xembedsniproxy,但它强依赖KDE的一堆组件,在niri下没法直接用。所以我找了别人用Rust重写的一个轻量独立版本xembed-sni-proxy来替代。

编译安装并配置成systemd用户服务开机自启:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 安装依赖
sudo pacman -S libx11 libxcb

# 拉取源码并编译安装(二进制会装到 ~/.cargo/bin/xembed-sni-proxy)
git clone https://somegit.dev/vikingowl/xembed-sni-proxy.git
cd xembed-sni-proxy
cargo install --path .

# 配置开机自启
install -Dm644 xembed-sni-proxy.service ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now xembed-sni-proxy

常用软件与实用技巧

VSCode检测不到密钥环

在niri下打开VSCode时,会遇到检测不到系统密钥环、登录状态保存不了的情况。编辑~/.vscode/argv.json,加上下面这行指定使用gnome-libsecret即可:

1
"password-store": "gnome-libsecret"

Fish配置代理函数

CachyOS默认的Shell是fish,终端里临时需要走代理时,每次手敲环境变量太麻烦,可以配两个快捷函数。创建~/.config/fish/functions/proxy.fish并写入下面内容(如果想在没执行过proxy的情况下也能直接调用noproxy,可以把两个函数拆成proxy.fish和noproxy.fish,或者直接放进~/.config/fish/config.fish里):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function proxy
    set -xg HTTP_PROXY "http://127.0.0.1:10808"
    set -xg HTTPS_PROXY "http://127.0.0.1:10808"
    echo "Proxy enabled."
end

function noproxy
    set -e HTTP_PROXY
    set -e HTTPS_PROXY
    echo "Proxy disabled."
end

修改桌面程序启动变量

前面给Firefox加硬解环境变量,或者给某个需要单独走代理、强制走Wayland的桌面应用改启动参数,都不建议直接改/usr/share/applications/下的原文件(软件更新时会被覆盖)。比较稳妥的做法是复制到用户目录~/.local/share/applications/下再改Exec字段:

1
2
3
4
5
# 复制桌面应用配置到本地
cp /usr/share/applications/horse.desktop ~/.local/share/applications/

# 编辑本地文件,修改 Exec 字段(以同时指定代理和 Wayland 后端为例)
Exec=env HTTP_PROXY="http://127.0.0.1:10808" HTTPS_PROXY="http://127.0.0.1:10808" chatgpt %U --ozone-platform=wayland

LaTeX环境配置

平时写论文还是离不开LaTeX,这里顺便记录一下在CachyOS下配本地TeX Live和VSCode插件的步骤。

安装TeX Live

完整版texlive-meta太大了,平时用不上那么多冷门宏包,直接按需安装下面这些常用的包就够用:

1
sudo pacman -S texlive-basic texlive-latex texlive-latexrecommended texlive-fontsrecommended texlive-latexextra texlive-bibtexextra texlive-mathscience texlive-binextra texlive-publishers

VSCode插件设置

在VSCode里安装LaTeX Workshop插件,然后在settings.json里加入下面的配置。我把编译产生的中间文件统一丢到了./tmp目录里,看着清爽很多,同时也配好了PdfLaTeX和XeLaTeX两套编译链:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  // 鼠标悬停,预览公式时,支持 boldsymbol 宏
  "latex-workshop.hover.preview.mathjax.extensions": [
      "boldsymbol"
  ],
  // 是否启用 IntelliSense,自动补全引用的包中的环境和命令
  "latex-workshop.intellisense.package.enabled": true,
  // 编译后的文件输出目录
  "latex-workshop.latex.outDir": "./tmp",
  // 默认编译引擎为上次使用的
  "latex-workshop.latex.recipe.default": "lastUsed",
  // 预览复杂公式,使用时需要通过 command palette (命令面板) 打开
  "latex-workshop.mathpreviewpanel.cursor.enabled": true,
  // 不允许弹窗显示错误信息
  "latex-workshop.message.error.show": false,
  // 不允许弹窗显示警告信息
  "latex-workshop.message.warning.show": false,
  "latex-workshop.latex.recipes": [
        {
            "name": "PdfLaTeX",
            "tools": [
                "pdflatexmk"
            ]
        },
        {
            "name": "XeLaTeX",
            "tools": [
                "xelatexmk"
            ]
        }
  ],
  "latex-workshop.latex.tools": [
      {
          "args": [
              "-synctex=1",
              "-pdfxe",
              "-interaction=nonstopmode",
              "-file-line-error",
              "-outdir=%OUTDIR%",
              "%DOC%"
          ],
          "command": "latexmk",
          "env": {},
          "name": "xelatexmk"
      },
      {
          "args": [
              "-synctex=1",
              "-pdf",
              "-interaction=nonstopmode",
              "-file-line-error",
              "-outdir=%OUTDIR%",
              "%DOC%"
          ],
          "command": "latexmk",
          "env": {},
          "name": "pdflatexmk"
      }
  ],

小结

从Windows切到CachyOS + niri这段时间用下来,整体体验比前两次折腾Arch舒服了不少。CachyOS省去了前期一大堆基础配置,niri的横向平铺用顺手之后确实很上头,剩下遇到的一些N卡、托盘和弹窗小坑也都在AI的帮忙下顺手修掉了。先把目前这套配置记录在这里,后面要是又踩了什么新坑再继续补充吧。

PS:本文使用了Gemini 4 Neon在我给出的大纲下进行了编写,只能说现在大模型的能力真的无敌了,给出我之前文章作为上下文进行学习,写出来的内容我都不怎么需要修改

参考链接